C++ cout 打印两次在循环中做

C++ cout print twice in do while loop

本文关键字:两次 循环 cout 打印 C++      更新时间:2023-10-16

系统这样做了:

请输入用户的全名

:请输入用户的全名:

它输出字符串"请输入用户的全名:"两次,如何更改代码以使其仅一次 cout。

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 )。

简单的解决方案是将 std::cout 语句移到 do-while 循环之外。

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

您正在执行输入操作而不检查结果,这是一个困难的编程和理解错误。请改为执行以下操作:

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

第一个条件检查输入是否成功(当输入流关闭时为 false),第二个条件检查读取行是否为非空。||的短路语义使第二次检查合法。

正如其他人指出的那样,问题是输入流上有一个额外的""字符。

与流行的答案相反,我不认为刷新(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<<() 来解析普通或常规输入;但是手动用户输入(即问题/答案)更难预测,并且用户输入line based(输入以""字符结尾,因为当他们点击 时缓冲区被刷新)。

因此,当我解析manual user input时,我总是使用 std::getline()。这样我知道我得到了他们的全部答案。它还允许我验证输入以确保没有键入错误。

 std::cout << "What is your agen";
 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 */ }