2017-09-20 45 views
0

美好的一天! 我想知道爲什麼我的程序(用C++ 11編寫)不斷切斷每個用戶輸入的第一個字符。 這裏是我的代碼:C++ 11 - 程序切斷每個輸入的首字母[使用:cin.ignore和getline)

#include <iostream> 
#include <string> 
#include <fstream> 

using namespace std; 

int main() { 

    ofstream dataFile; 
    dataFile.open("studentData.txt"); 

    string set1, set2, set3, set4; 

cout << "How long was the fish when you first measured it?" << endl; 
cin.ignore(); 
getline(cin, set1); 
dataFile << set1 << endl; 

cout << "How long is the fish now?" << endl; 
cin.ignore(); 
getline(cin, set2); 
dataFile << set2 << endl; 

cout << "Where was the fish when you first tagged it?" << endl; 
cin.ignore(); 
getline(cin, set3); 
dataFile << set3 << endl; 

cout << "Where is the fish now?" << endl; 
cin.ignore(); 
getline(cin, set4); 
dataFile << set4 << endl; 

dataFile.close(); 

return 0; 
} 

這裏是輸出,如果輸入如下: 設置1 - 12英寸 設置2 - 24英寸 SET3 - 瓦爾多斯塔,格魯吉亞 SET4 - 邁阿密,佛羅里達

2 inches 
4 inches 
aldosta, Georgia 
iami, Florida 

這是爲什麼發生?我讀過使用cin.ignore和cin.getline,但是,我無法找到一個合適的解決方案。這是我的語法嗎?我不正確地使用這些功能嗎? 請注意,我是初學C++的編程人員! ^^

- 謝謝!

+0

這是因爲顯示的代碼使用'<<'運算符將'std :: getline'和格式化輸入操作混合在一起;並使用'ignore()'不是一個通用的解決方案。除非你完全理解兩者之間的相互作用,否則會出現這樣的令人驚訝的結果。在完全理解它們的工作方式之前,或者只使用'std :: getline',或者只使用'<<'運算符來讀取輸入。 –

+0

馬上關閉:'cin.ignore(); getline(cin,set1);'有什麼要忽略的,但是第一個輸入字符? – user4581301

+0

擺脫對'cin.ignore()'的調用。 –

回答

0

刪除電話cin.ignore(),因爲它忽略了你的第一個字符。以下代碼適用於我。

#include <iostream> 
#include <string> 
#include <fstream> 

using namespace std; 

    int main() { 

     ofstream dataFile; 
     dataFile.open("studentData.txt"); 

     string set1, set2, set3, set4; 

    cout << "How long was the fish when you first measured it?" << endl; 
    getline(cin, set1); 
    dataFile << set1 << endl; 

    cout << "How long is the fish now?" << endl; 
    getline(cin, set2); 
    dataFile << set2 << endl; 

    cout << "Where was the fish when you first tagged it?" << endl; 
    getline(cin, set3); 
    dataFile << set3 << endl; 

    cout << "Where is the fish now?" << endl; 
    getline(cin, set4); 
    dataFile << set4 << endl; 

    dataFile.close(); 

    return 0; 
    } 
相關問題