无法将字符串与"y"进行比较

cannot compare a string to "y"

本文关键字:比较 字符串      更新时间:2023-10-16

我正在计算代码中有多少y。因为你可以看到我的文件中有一些y。但计数器仍然是零。我做错了什么?(注:我知道它们都是if(word=="y")我也要数n。这里应该不重要)

inline ifstream& read(ifstream& is, string f_name)
{
is.close();
is.clear();
is.open(f_name.c_str());
return is;
}
//main function
int main ()
{
string f_name=("dcl");
ifstream readfile;
read(readfile, f_name);
string temp, word;
istringstream istring;
int counter=0, total=0;
while(getline(readfile,temp))
{
    istring.str(temp);
    while(istring>>word)
    {
        cout<<word<<"_"<<endl;
        if(word=="y")
            ++counter;
        if(word=="y")
            ++total;
    }
    istring.clear();
}
cout<<counter<<" "<<total<<" "<<endl;
return 0;   
}

,我的输出是

Date_
9am_
Break_
Lunch_
Walk_
Break_
---------------------------------------------------_
11/09/11_
y_
y_
y_
y_ 
y_
_
0 0 

my input codes:

//check list for daily activities
#include <iostream>
#include <string>
#include <fstream>
#include <stdexcept>
using namespace std;
//inline function
inline ofstream& write(ofstream& input, string& f_name); //write to a file function
inline void tofile(ofstream& w2file, const string& s);  //output format
//main function
int main ()
{
string f_name="dcl";
cout<<"date: "<<ends;
string temp;
cin>>temp;
ofstream checklist;
write(checklist,f_name);
tofile(checklist,temp);
cout<<"start the day at 9am? [y/n]"<<ends;
cin>>temp;
tofile(checklist,temp);
cout<<"a break every 1 hr? [y/n]: "<<ends;
cin>>temp;
tofile(checklist,temp);
cout<<"lunch at noon? [y/n]: "<<ends;
cin>>temp;
tofile(checklist,temp);
cout<<"20 min walk? [y/n]: "<<ends;
cin>>temp;
tofile(checklist,temp);
cout<<"a break every 1 hr in the afternoon? [y/n]: "<<ends;
cin>>temp;
tofile(checklist,temp);
checklist<<endl;
cout<<endl;
return 0;
}
inline ofstream& write(ofstream& input, string& f_name)
{
input.close();
input.clear();
input.open(f_name.c_str(),ofstream::app);
return input;
}
inline void tofile(ofstream& w2file, const string& s)
{
w2file<<s<<"t"<<ends;
}

尝试std::count(word.begin(), word.end(), 'y')计算单词中'y'的出现次数,并将其累加到总计数器中。

问题在于程序中生成DCL文件的tofile函数。当你写每行时,你基本上是用一个制表符分隔每个字段,然后用一个空字符做<< "t" << ends;,然后再读这行,用istringstream,但istringstream用空格字符分隔。因此,您需要将"t"更改为" "并删除<< ends

inline void tofile(ofstream& w2file, const string& s)
{
    w2file << s << " ";
}

如果我在源代码的开头添加适当的include和"using namespace std",并使用g++进行编译,然后将其作为文件"dcl"的内容在输出中运行,它会在末尾打印" 5.5 "——也就是说,您的代码工作正常。