2017-03-08 9 views
0

これはこれまで私が持っているものです... このプログラムのポイントは、ファイル内の単語の数を表示し、同じファイルの単語数の文字数を取得することです。ファイル内の文字数を読み取る方法は?

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

    using namespace std; 

    int main() 
    { 
     int numberOfWords = 0, i = 0; 
     char letters = 0; 
     string line; 

     ifstream myFile; 
     myFile.open("text.txt"); 

    //I got this to work, it displays the number of words in the file 
    if (myFile.is_open()) 
    { 
     while (!myFile.eof()) 
    { 
     myFile >> line; 
     i++; 
    } 
    numberOfWords = i; 

    //this is where I'm having trouble. I can't get this code to work for it to display the number of letters in the file. 
    while (!myFile.eof()) 
    { 
     //cout << line << endl; 
     letters = line.length(); 
     letters++; 
    } 
} 
     myFile.close(); 

     cout << "There are " << numberOfWords << " words in the textfile\n" 
      << "There are " << letters << " letters in those " <<  numberOfWords << " words\n"; 

     cin.get(); 

     return 0; 

}

+4

を横断に行くようにジャストhttp://stackoverflow.com/questions/5605125/why-is-iostreameof([こちら]をご覧単語の文字の数を数えます-inside-a-loop-condition-considered-wrong)を実行してください。 –

+0

'!myFile.eof()'は、2番目のループに来たときに既にtrueでした。ファイルからの読み込みを再開するためには、少なくとも 'myFile.clear()'と 'myfile.seek(0)'を呼び出す必要があります。 –

+0

なぜあなたは2番目の時間が必要ですか?あなたは、同じループ内で文字の計算の数を得ることができます。 'while(myfile >> line){++ numberOfWords;文字+ =行。長さ(); } ' – JustRufus

答えて

0

あなたは間違ってそれをやっています。

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

using namespace std; 

int main() 
{ 
    int numberOfWords = 0, i = 0; 
    int letters = 0; 
    string line; 

    ifstream myFile; 
    myFile.open("text.txt"); 

//I got this to work, it displays the number of words in the file 
if (myFile.is_open()) 
{ 
    while (!myFile.eof()) 
    { 
     myFile >> line; 
     letters += line.length(); 
     //letters++; 
     i++; 

    } 
numberOfWords = i; 

//this is where I'm having trouble. I can't get this code to work for it to display the number of letters in the file. 
//while (!myFile.eof()) 
//{ 
    //cout << line << endl; 

//} 
} 
myFile.close(); 

    cout << "There are " << numberOfWords << " words in the textfile\n" 
     << "There are " << letters << " letters in those " <<  numberOfWords << " words\n"; 

    cin.get(); 

    return 0; 
} 

あなたがライン

関連する問題