无法将字符串与"y"进行比较
cannot compare a string to "y"
我正在计算代码中有多少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 "——也就是说,您的代码工作正常。
相关文章:
- 视觉C++使用 map 来比较字符串中的每个单词
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 比较字符串的 GetLine 工作一次,然后比较之后不起作用
- C++使用关系运算符比较字符串
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- C++ TCP 服务器比较字符串失败
- 如何在不复制的情况下比较字符串的一部分?
- 比较 C++ 字符串打印中的两个整数数组
- 如何比较字符串形式的临时变量
- std::out_of_range 比较字符串中的符号时出错
- 比较字符串大小写不区分的简单方法是什么?
- 比较字符串忽略 NUL
- 比较字符串(arduino)时出现问题
- 如何在C++中比较字符串
- 比较字符串对象等于向量中的元素
- C 比较字符串操作速度
- 需要比较字符串的某些元素
- 比较字符串 .c_str() 和普通字符串的差异
- C 比较字符串的字符
- 通过使用两个不同的队列比较字符串