这是我到目前为止所拥有的...... 这个程序的目的是显示文件中的单词数,并获得同一文件的单词数中的字母数。
#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;
}
答案 0 :(得分: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;
}
在遍历线路时,只计算单词的字母数