2016-06-28 14 views
0

ファイルを読み込んで行に出力し、文字数、行数、空白以外の文字数、単語数を数えてみます。私は終わったと思っていますが、私は単語の数を数える方法を理解できません。また、私はそれを実行するときに最初を除いて、すべての行の最初の文字をカットします。ファイルと単語の読み込み

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

using namespace std; 

int main() 
{ 
    int line_number = 0; 
    char words; 
    int number_of_spaces = 0; 
    int number_of_lines = 0; 
    int number_of_characters = 0; 
    int number_of_words = 0; 
    int count = 0; 
    char character; 
    string word; 
    int n = 0; 
    string line; 
    ifstream myFile; 
    string file; 
    cout <<"Enter file name: "; 
    getline(cin,file); 


    myFile.open(file.c_str()); 
    char output[100]; 



    if(myFile.is_open()) 
    { 

     cout << " " << endl; 

     while(getline (myFile, line)) 
     { 
      line_number += 1; 
      cout << "Line: " << line_number << " "; 
      cout << line << endl; 

      number_of_characters += line.length(); 

      for (int i = 0; i < line.length(); i++) 
      { 
       if(line[i] == ' ' || line[i] == '/t') 
       { 
        number_of_spaces++; 
       } 
      } 

      myFile.get(character); 
      if (character != ' ' || character != '/n') 
      { 
       number_of_lines += 1; 
      } 


     } 




     cout << " " << endl; 
     cout << number_of_characters << " characters, " << endl; 
     cout << number_of_characters - number_of_spaces << " non whitespace characters, " << endl; 
     cout << number_of_words << " words, " << endl; 
     cout << number_of_lines << " lines." << endl; 

    } 

    myFile.close(); 

    system("Pause"); 
    return 0; 
} 
+0

'getline'は行全体を使います。ですから、 'myFile.get()'を呼び出すことで、後続の行の最初の文字が失われてしまいます。また、 ''/n ''ではなく '' \ n ''です。 – kfsone

+0

これらの行を削除することができます: 'myFile.get(character); if(文字!= '' ||文字!= '/ n') { number_of_lines + = 1; } ' – BlackMamba

答えて

1

単語を1語ずつ読むには、>>演算子を使用します。このコードはうまくいくはずです:

std::string word; 
int counter = 0; 
while (myFile >> word) 
{ 
    counter++; 
} 
関連する問題