#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::string
的operator==
,它将执行正确的操作:比较这两个字符串。