我正在尝试计算我的代码中有多少个 y。因为您可以看到我的文件中确实有一些 y。但计数器仍然为零。我究竟做错了什么? (p.s 我知道他们都是“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
我的输入代码:
//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' 的出现次数并将其累加到总计数器.
关于c++ - 无法将字符串与 "y"进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8074380/