![](/img/trans.png)
[英]C++ getline inside while loop missing first letter. Does not work without cin.ignore?
[英]C++11 - Program cuts off first letter of every input [Using: cin.ignore and getline)
美好的一天! 我想知道為什么我的程序(用C ++ 11編寫)總是切斷每個用戶輸入的第一個字符。 這是我的代碼:
#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;
}
如果輸入如下,則為輸出:set1-12英寸set2-24英寸set3-喬治亞州瓦爾多斯塔set4-佛羅里達州邁阿密
2 inches
4 inches
aldosta, Georgia
iami, Florida
為什么會這樣呢? 我已經閱讀了有關使用cin.ignore和cin.getline的信息,但是,我找不到合適的解決方案。 是我的語法嗎? 我使用功能不正確嗎? 請記住,我是C ++編程的初學者! ^^
- 謝謝!
刪除對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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.