2017-02-14 5 views
-1

Итак, здесь я получил код, который подсчитывает количество строк символов и слов в файле. Теперь мне нужно реализовать одно и то же для нескольких файлов. В основном мой код должен читать количество слов и строк символов в каждом файле и должен давать общее количество слов и строк символов (сложение количества слов и строк символов из каждого файла. Мне также нужна помощь, выполняющая код для слабо сформированных аргументов , файл не найден и непризнанные аргументы. Вот мой код, я попытался его скомпилировать, но он может читать только количество символов и символов в каждом файле, а не суммировать общее количество. Спасибо, ребята. Любая помощь высоко оценили или предложения.Как подсчитать общее количество слов и строк символов в двух файлах и добавить их в соответствие с итогами?

#include <iostream> 
#include <fstream> 
#include <iomanip> 
#include <string> 




using namespace std; 

int main(int argc, char*argv[]) 
{ 

if (argc<2){ 
    cout<<"You did not enter enough arguments, Please try again, close this cd window and enter the correct filename"<<endl; 
} 
else{ 
    string filename; 
    ifstream thefile; 
    int i; 
    for(i=1,i<=argc;(i++);){ 
    filename=argv[i]; 
    int charactercounter=0, linecounter=1, wordcounter=1, totalLines, totalWords,totalCharacters; 
    thefile.open(filename); 
     if(!thefile.is_open()){ 
      cout<<"file does not exist"<<endl; 
     } 
     else if(thefile.fail()){ 
      cout<<"arguments can't be recognized"<<endl; 
     } 

    if(thefile.is_open() && thefile.good()){ 
    while(!thefile.eof()){ 
     char ch; 
     while(ch!=EOF){ 
      charactercounter++; 
      totalCharacters=totalCharacters+charactercounter; 
      if (ch=='\n') 
       linecounter++; 
       totalLines=totalLines+linecounter; 
       if (ch==' ') 
       wordcounter++; 
       totalWords=totalWords+wordcounter; 
      ch=thefile.get(); 

     } 
     } 




     cout<<setw(12)<<"Lines"<<' '<< linecounter; 
     cout<<' '; 
     cout<<setw(12)<<"words"<<' '<< wordcounter; 
     cout<<' '; 
     cout<<setw(12)<<"characters"<<' '<< charactercounter; 
     cout<<' '; 
     cout<<setw(12)<<"filename"<<' '<<argv[i]; 
     cout<<' '; 
     cout<<setw(12)<<"totallines"<<' '<<totalLines; 
     cout<<' '; 
     cout<<setw(12)<<"totalwords"<<' '<<totalWords; 
     cout<<' '; 
     cout<<setw(12)<<"totalchars"<<' '<<totalCharacters; 
     cout<<' '; 


     thefile.close(); 
    } 

    } 
    } 

}

+1

Добро пожаловать в Переполнение стека. Пожалуйста, найдите время, чтобы прочитать [The Tour] (http://stackoverflow.com/tour) и обратитесь к материалу из [Справочного центра] (http://stackoverflow.com/help/asking) о том, что и как вы можете спросите здесь. –

+2

Правильный инструмент для решения таких проблем - ваш отладчик. Перед тем, как просить о переполнении стека, вы должны пропустить свой код по очереди *. Для получения дополнительной информации, пожалуйста, прочтите [Как отлаживать небольшие программы (Эрик Липперт)] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Как минимум, вы должны \ [изменить] ваш вопрос, чтобы включить пример [Минимальный, полный и проверенный] (http://stackoverflow.com/help/mcve), который воспроизводит вашу проблему, а также замечания, сделанные вами в отладчик. –

+0

Этот код непросто для человека читать, и это затрудняет поиск ошибок. Должен использовать функцию/класс для разных частей программы. Таким образом, вы можете написать модульные тесты, чтобы проверить, какая функция/класс не ведет себя так, как ожидалось, вместо того, чтобы много раз искать всю программу для поиска каждой ошибки. Разработка хорошей архитектуры программного обеспечения до написания программы и написания модульных тестов может помочь. –

ответ

0

Добавлены некоторые комментарии, функции и классы, чтобы легче читать код.

Я также пытаюсь сохранить ошибки в программе.

#include <iostream> 
#include <fstream> 
#include <iomanip> 
#include <string> 

using namespace std; 
// ----------------------------------------------------------------------------- 
bool argc_checker(const int argc, const char* const argv[]) { 
    // Check commandline arguments 
    // If no problem, return true. Otherwise, return false. 
    if (argc < 2) { 
     cout << "You did not enter enough arguments, Please try again, " 
       "close this cd window and enter the correct filename" << endl; 
     return false; 
    } 
    return true; 
} 
// ----------------------------------------------------------------------------- 
bool check_file(const ifstream& thefile) { 
    // Return true if the file is ok. Otherwise, return false 
    if (!thefile.is_open()) { 
     cout << "file does not exist" << endl; 
     return false; 
    } 
    if (thefile.fail()) { 
     cout << "arguments can't be recognized" << endl; 
     return false; 
    } 
    if (thefile.is_open() && thefile.good()) { 
     return true; 
    } 
    return false; 
} 
// ----------------------------------------------------------------------------- 
class Word_counter { 
    // Count the number of character, words, and lines by taking characters 
    // one by one. 
public: 
    Word_counter() { reset(); } 
    void take(const char ch) { 
     ++_n_chars; 
     if (ch == ' ') ++_n_words; 
     if (ch == '\n') ++_n_lines; 
    } 
    void reset() { 
     // Reset the word counter. 
     _n_chars = 0; 
     _n_words = 1; 
     _n_lines = 1; 
    } 
    const int n_chars() const { return _n_chars; } 
    const int n_words() const { return _n_words; } 
    const int n_lines() const { return _n_lines; } 
private: 
    int _n_chars; 
    int _n_words; 
    int _n_lines; 
}; 
// ----------------------------------------------------------------------------- 
class Total_word_counter { 
    // Take a word counter and add its count to total counts. 
public: 
    Total_word_counter() { reset(); } 
    void take(const Word_counter& wc) { 
     _n_total_chars += wc.n_chars(); 
     _n_total_lines += wc.n_lines(); 
     _n_total_words += wc.n_words(); 
    } 
    void reset() { 
     // Reset the total word counter 
     _n_total_chars; 
     _n_total_lines; 
     _n_total_words; 
    } 
    const int n_total_chars() const { return _n_total_chars; } 
    const int n_total_words() const { return _n_total_words; } 
    const int n_total_lines() const { return _n_total_lines; } 
private: 
    int _n_total_chars; 
    int _n_total_words; 
    int _n_total_lines; 
}; 
// ----------------------------------------------------------------------------- 
template <typename T> 
void simple_print_table(const std::string& name, const T& thing) { 
    cout << setw(12) << name << ' ' << thing << ' '; 
} 
// ----------------------------------------------------------------------------- 
int main(int argc, char *argv[]) { 
    // check if arguments are ok. if not, exit the program. 
    if (!argc_checker(argc, argv)) exit(1); 

    // Create word counters 
    Word_counter wc; 
    Total_word_counter total_wc; 

    // loop over each commandline argument 
    for (int i = 1, i <= argc; (i++);) { 
     string filename(argv[i]); 
     ifstream the_file(filename); 

     // check if file is ok. if not skip to next cycle of the for loop. 
     if (!check_file(the_file)) { 
      the_file.close(); 
      continue; 
     } 
     // loop over each character of the_file. 
     char ch; 
     while (!the_file.eof() && (ch != EOF)) { 
      wc.take(ch); 
      ch = the_file.get(); // pass each char to the word counter 
     } 
     total_wc.take(wc); // add result of word counter to total_wc 
     // Print result of counting 
     simple_print_table("Lines", wc.n_lines()); 
     simple_print_table("words", wc.n_words()); 
     simple_print_table("characters", wc.n_chars()); 
     simple_print_table("totallines", total_wc.n_total_lines()); 
     simple_print_table("totalwords", total_wc.n_total_words()); 
     simple_print_table("totalchars", total_wc.n_total_chars()); 
     // Rest word counter 
     wc.reset(); // reset the wc so it is ready to count next file 
     // Close the file 
     the_file.close(); 
    } 
} 
// ----------------------------------------------------------------------------- 
+0

В вашем коде слишком много вложенных уровней скобок '{}'. Это делает код очень трудным для чтения. –

+0

О, черт возьми, за то, что я стараюсь вынуть скобки и сделать это спасибо тебе много! Ваше лучшее. –