在程序中打印单词的计数:"the",从包含句子的.txt文件中给出计数= 0,即使"the"计数不为零


#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ifstream fin;
char ch[30];
int count = 0;
fin.open("story.txt");
while (!fin.eof())
{
fin>>ch;
if(ch == "the" || ch == "The")
{
count++;
cout<<" "<<ch;
}
}
fin.close();
cout<<" Number of the's in the file : "<<count;

}

不应该使用strcompi((函数。(或有助于将"ch"与"the"进行比较的任何其它功能(

计数给出零输出,因为if条件不起作用

这是我的代码,这里可能有什么问题。**

不能将char数组与==进行比较,但可以与std::string进行比较。

更改

char ch[30];

std::string ch;

如果用std::string ch替换char ch[30];,它看起来会起作用。也许需要一些小的调整。

它不起作用的原因是ch == "the"测试作为指针衰减的char ch[30]是否指向与"指针"相同的内存位置;";字面意义的但事实并非如此。

如果使用std::string,则会调用std::stringoperator==,它将执行正确的操作:比较这两个字符串。

相关内容

最新更新