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

标签 c++ g++

我正在尝试计算我的代码中有多少个 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/

相关文章:

c++ - C++ 中的 BFS 实现

c++ - OpenGL 无法使用 Shaders Mac 进行渲染

c++ - 如何使 Angular 落正确显示(看里面的图片)?

c++ - Makefile 重复符号

c++ - 如何为 jsoncpp 编写 cmake 模块?

c++ - 对 `gsl_vector_free' 的 undefined reference

C++ get 方法 - 按值或按引用返回

c++ - gcc 4.7.2 虚函数错误

C++ 枚举问题和 g++ 中可能的循环依赖

c++ - 尽管在参数中提供了所有需要的库,但为什么编译器会抛出 "undefined reference to ..."