[英]Using cin.get() to discard unwanted characters from the input stream in c++
我正在為我的C ++類分配作業。 給出以下代碼。 指導說明輸入六個字符串並觀察結果。 當我這樣做時,第二個用戶提示就會通過,程序結束。 我可以肯定的原因是,第一個cin.getline()在輸入流中留下了多余的字符,這使第二個cin.getline()發生混亂。 我將使用cin.get,循環或同時使用兩者,以防止多余的字符串字符干擾第二個cin.getline()函數。
有小費嗎?
#include <iostream>
using namespace std;
int main()
{
char buffer[6];
cout << "Enter five character string: ";
cin.getline(buffer, 6);
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
cout << "Enter another five character string: ";
cin.getline(buffer, 6);
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}
你是對的。 第一次輸入后,換行符保留在輸入緩沖區中。
第一次閱讀后,嘗試插入:
cin.ignore(); // to ignore the newline character
還是更好:
//discards all input in the standard input stream up to and including the first newline.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
為此,您必須#include <limits>
標頭。
編輯:雖然使用std :: string會好得多,但以下修改后的代碼有效:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
char buffer[6];
cout << "Enter five character string: ";
for (int i = 0; i < 5; i++)
cin.get(buffer[i]);
buffer[5] = '\0';
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
cout << "Enter another five character string: ";
for (int i = 0; i < 5; i++)
cin.get(buffer[i]);
buffer[5] = '\0';
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.