簡體   English   中英

C ++ cout在do while循環中打印兩次

[英]C++ cout print twice in do while loop

系統這樣做:

請輸入用戶的全名:請輸入用戶的全名:

它兩次輸出字符串“請輸入用戶的全名:”,我該如何更改代碼以使其僅出現一次

string fullname = "";

    do
    {
    cout << "Please input the Full Name of the user: ";
    getline (cin,fullname);
    }while(fullname.length()<1);

C ++是什么導致系統輸出兩次

您可以嘗試刷新輸入流以擺脫剩余的換行符: std::cin.ignore(x); (其中x是要忽略的字符數,例如INT_MAX )。

您正在執行輸入操作而沒有檢查結果,這是一個困難的編程和理解錯誤。 改為:

for (std::string line; ; )
{
    std::cout << "Name: ";
    if (!std::getline(std::cin, line) || !line.empty()) { break; }
}

第一個條件檢查輸入是否成功(在關閉輸入流時為假),第二個條件檢查讀取行是否為非空。 ||的短路語義 使第二張支票合法。

一種簡單的解決方案是將std :: cout語句移至do-while循環之外。

string fullname = "";
cout << "Please input the Full Name of the user: ";
do
{ 
    getline (cin,fullname);
}while(fullname.length()<1);

正如其他人指出的那樣,問題是輸入流上有一個額外的'\\ n'字符。

與流行的答案相反,我認為刷新(ignore())當前輸入不是一個好的解決方案。 您正在治療症狀不是問題。 如果您使用的是ignore(),則可能會丟棄您可能真正想要的用戶輸入或可能檢測到用戶錯誤的內容:

> Input Your age
> 36xxxx

// If you use
std::cin >> age;
// Then sometime later in your code you use
// ignore to make sure that you have "correctly" skipped to the next new line
std::ignore(std::numeric_limits<std::streamsize>::max(), '\n');

// You have now just ignored the fact that the user typed xxx on the end of the input.
// They were probably doing that to force an error in the code or something else erroneous
// happened but you just missed it with std::ignore()

最好的解決方案是不要陷入這種情況。
此問題是由於使用operator<<()std::getline()來分析用戶輸入而引起的。 我喜歡使用operator<<()解析普通或常規輸入; 但是手動用戶輸入(即Question / Answer)更難預測,並且用戶輸入line based (輸入以'\\ n'字符結尾,因為當他們按下<enter>時緩沖區會被刷新)。

結果,當我解析manual user input我總是使用std :: getline()。 這樣,我知道我得到了他們的全部答案。 它還使我可以驗證輸入,以確保沒有鍵入錯誤。

 std::cout << "What is your age\n";

 std::string        line;
 std::getline(std::cin, line);   // Get user input

 // Use stream for easy parsing.
 std::stringstream  linestream(line);

 // Get value we want.
 linestream >> age;

 // Validate that we have not thrown away user input.
 std::string error;
 linestream >> error;
 if (error.length() != 0) { /* do stuff to force user to re-input value */ }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM