我正在尝试计算输入文件中的大写和小写字母,数字位数和单词数。我已经完成了这个,但是,我的字数是一个。输入文件中有52个单词,但我的计数是53.这会导致什么?所有其他的(大写,小写和数字)都是正确的......
以下是我所拥有的:
using namespace std;
int main()
{
fstream inFile;
fstream outFile;
string fileName("");
string destName("");
char c = 0;
///////string wrdRev("");/////////
int numCount = 0;
int capCount = 0;
int lowCount = 0;
int wordCount = 0;
cout << "Please enter file name: ";
getline(cin, fileName);
cout << endl;
inFile.open(fileName, ios::in);
if (inFile.good() != true) {
cout << "File does not exist!\n" << endl;
return 0;
}
else{
reverse(fileName.begin(), fileName.end());
destName += fileName;
}
outFile.open(destName, ios::in);
if (outFile.good() == true){
cout << "File '" << destName << "' already exists!\n" << endl;
return 0;
}
else {
outFile.clear();
outFile.open(destName, ios::out);
while(inFile.good() != false){
inFile.get(c);
if(isupper(c)){
capCount++;
}
else if(islower(c)){
lowCount++;
}
else if(isdigit(c)){
numCount++;
}
else if(isspace(c)){
wordCount++;
}
}
outFile << "There are " << capCount << " uppercase letters." << endl;
outFile << "There are " << lowCount << " lowercse letters." << endl;
outFile << "There are " << numCount << " numbers." << endl;
outFile << "There are " << wordCount << " words." << endl;
}
inFile.close();
outFile.close();
return 0;
}
任何帮助将不胜感激。谢谢。
答案 0 :(得分:4)
ios::good()
返回true
。所以你再来一次循环体。上次读取失败时,字符不变,因为它显然是一个空白字符,字数会增加。
您通常不应使用此good()
,eof()
等作为输入结束的测试。这样做:
while (inFile.get(c)) {
//...
}