2

系统这样做了:

请输入用户全名:请输入用户全名:

它输出字符串“请输入用户的全名:”两次,我如何更改代码以使其只输出一次

string fullname = "";

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

C++是什么导致系统输出两次

4

4 回答 4

3

您可以尝试刷新您的输入流以摆脱剩余的换行符:( std::cin.ignore(x); 作为x要忽略的字符数,例如INT_MAX)。

于 2012-08-14T14:57:40.843 回答
2

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

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

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

于 2012-08-14T14:59:51.480 回答
2

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

string fullname = "";
cout << "Please input the Full Name of the user: ";
do
{ 
    getline (cin,fullname);
}while(fullname.length()<1);
于 2012-08-14T15:01:21.393 回答
0

正如其他人指出的那样,问题在于输入流上有一个额外的 '\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<<()用来解析正常或常规输入;但是手动用户输入(即问题/答案)更难预测,用户输入是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 */ }
于 2012-08-14T15:59:04.230 回答