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;
}
은 [여기]를 보라 라인 (http://stackoverflow.com/questions/5605125/why-is-iostreameof 횡단에 가서
그냥 단어의 문자 수를 계산 -inside-a-loop-condition-considered-wrong)를 실행하십시오. –
두 번째 루프를 수행 할 때'! myFile.eof()'는 이미 true였습니다. 적어도 myFile.clear()와 myfile.seek (0)를 호출하여 파일에서 다시 읽기를 시작해야한다. –
왜 두 번째가 필요합니까? 같은 루프에서 글자 수를 계산할 수 있습니다. 'while (myfile >> line) {++ numberOfWords; 글자 + = line.length(); } ' – JustRufus