2011-11-10 61 views
0

我正在計算我的代碼中有多少個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; 
} 
+0

您的代碼適用於我(在添加適當的標頭之後)。我將你的輸出中的_分離出來,生成一個文本文件,編譯程序,然後運行它,得到「5 5」的結果。 – wollw

+0

當我編譯程序並用一些「y」行填充文件時,我得到「5 5」作爲預期的最終輸出。 – aschepler

+0

也許這是我的字符編碼?當我用gedit打開dcl的時候。它有一些有數字的奇怪盒子。 – ihm

回答

1

問題在於您的程序中的tofile函數生成DCL文件。在寫每一行時,基本上是通過製表符分隔每個字段,然後執行<< "\t" << ends;,然後讀取該行並使用它與istringstream分開,但使用空格字符分隔istringstream。所以,您需要更改"\t"" "並刪除<< ends

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

作爲一個方面,你只需要一個if ...你可以這樣做:if(0 == word.compare(「y」))++ counter,++ total; –

+1

'=='運算符適用於'string'和'char *'。 –

+0

仍然爲0 0;是因爲我在linux中編譯它?我需要將它保存爲一個txt文件嗎?我只是touch'ed dcl(文件名) – ihm

2

嘗試std::count(word.begin(), word.end(), 'y')算「Y」的出現次數一個字內和積累,爲一個總計數器。

0

如果我添加相應的包括和「使用命名空間std」到你的源代碼開始,並與G ++編譯,然後運行它針對的文件「DCL」的內容,你的輸出,它打印「 5 5「 - 即你的代碼工作正常。您的輸入必須以某種方式非常奇怪...

+0

我更新了我的輸入代碼。 – ihm

相關問題