我想编写一个 c++ 程序,其中我有一个文件,我想看看单词 "good" 在文件中出现的次数。为什么这不起作用



所以这就是我所做的。这也是我在做单词搜索代码时主要使用的逻辑。我想看看能不能找到这个字符然后看是否有与good匹配的字母。如果它们匹配,那么我执行count++来计数,最后输出结果:-


#include<iostream> //headers
#include<fstream>
using namespace std;
int main()
{

char arr[10000];
//declaration
fstream fileis;

fileis.open("fileis.txt",ios::in);

while (!fileis.eof( ))      
{     //reading loop

fileis>>arr;
cout<<arr<<endl;  
}

int count=0;

for(int i=0; arr[i] != ''; i++)  //main loop
{
if(arr[i] == 'g' && arr[i+1] == 'o' && arr[i+2] == 'o' && arr[i+3] == 'd') //condition to check if the word is there
{
count++;     
}
}

fileis.close();

cout<<"The word good appeared "<<count<<" times."<<endl;

return 0;

}

我的建议是:

std::string word;
count = 0;
//...
while (fileis >> word)
{
// Convert word to all lower case for easy comparison.
std::transform(word.begin(), word.end(), word.begin(), tolower);
if (word == "good") ++count;
}

上面的代码片段有一些OP需要查找的问题(例如当在"good"之后读入标点符号时会发生什么)。

默认情况下,从流中读取字符串以"word"分隔。

最新更新