我正在計算我的代碼中有多少個y。既然你可以看到我的文件中有一些y。但櫃檯仍然是零。我究竟做錯了什麼? (PS我知道他們都是「如果(字==」 Y「)」我要計數n太,應該沒有真正的問題在這裏)無法將字符串與「y」進行比較
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;
}
您的代碼適用於我(在添加適當的標頭之後)。我將你的輸出中的_分離出來,生成一個文本文件,編譯程序,然後運行它,得到「5 5」的結果。 – wollw
當我編譯程序並用一些「y」行填充文件時,我得到「5 5」作爲預期的最終輸出。 – aschepler
也許這是我的字符編碼?當我用gedit打開dcl的時候。它有一些有數字的奇怪盒子。 – ihm