[英]C++ cout in while loop prints twice
我修改了Bjarne Stroustrup編程:C ++中的原理和實踐中的代碼,試圖檢查給定的輸入是否有效:
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter your first name and age: ";
string first_name = "???";
int age = -1;
cin >> first_name >> age;
while (!cin) {
cin.clear();
cout << "Sorry, can you enter that again? ";
cin >> first_name >> age;
}
cout << "Hello, "<<first_name<<"! (age "<<age<<")\n";
return 0;
}
這可以按預期工作,除了"Sorry, can you enter that again? "
這兩個字樣被打印兩次,一次是在第二次輸入之前,一次是之后。
任何人都知道為什么會發生這種情況? 謝謝。
清除失敗位是不夠的,還必須清除輸入緩沖區中的任何剩余字符。 此外,代碼看起來比必要的更復雜。 以下作品:
std::string name;
int age;
std::cout << "Please enter your name & age: ";
while (not (std::cin >> name >> age)) {
std::cout << "Sorry, can you enter that again? ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "Hello " << name << " (" << age << ")\n";
哦,是的,不要忘記刷新輸出流,我不認為這將自動為您完成。
也就是說,標准輸入/輸出流就是流 ,所以它們實際上並不適合交互式輸入。 您應該使用適當的庫,例如readline
或ncurses
。
為了說明為什么這很重要,想象用戶輸入“ foo42
”並按回車鍵。 你希望程序現在說“對不起,你能再次輸入嗎?”但事實並非如此。 相反,它溫順地等待用戶輸入第二個令牌。 從可用性的角度來看,這肯定不是你所期望的。
這取決於你輸入的內容!
輸入"Tim 29"
:作品,“你好蒂姆(29)”。
輸入"Tim Tom 29"
:作品,一次重復,“你好湯姆(29)”。
輸入"Tim Tom Tina 29"
:作品,兩次重復,“你好蒂娜(29)”。
我假設你正在嘗試第三個。 第一個失敗是Tom
,他不是一個數字。 重置錯誤狀態很好,但它沒有擺脫Tom
。 我們仍然需要再次失敗的嘗試才能消耗他( Tina
失敗了,那時他不是一個數字)。 只有這樣,我們才准備好Tina
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.