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

时间:2011-11-10 02:40:33

标签: c++ g++

我正在尝试计算代码中有多少y。因为你可以看到我的文件中有一些y。但柜台仍为零。我究竟做错了什么? (p。我知道他们都是“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;
}

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

问题在于程序中的tofile函数生成DCL文件。在编写每一行时,您基本上将每个字段用制表符分隔,然后通过执行<< "\t" << ends;然后读取该行并将其与istringstream一起使用,但istringstream使用空字符用空格字符分隔。因此,您需要将"\t"更改为" "并删除<< ends

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

答案 2 :(得分:0)

如果我将相应的includes和“using namespace std”添加到源的开头并使用g ++进行编译,则将其作为文件“dcl”的内容针对您的输出运行,它将打印“5 5”at结束 - 即,你的代码工作正常。你的输入必须以某种方式非常特殊......

相关问题