C++ cout 打印两次在循环中做
C++ cout print twice in do while loop
系统这样做了:
请输入用户的全名:请输入用户的全名:
它输出字符串"请输入用户的全名:"两次,如何更改代码以使其仅一次 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 */ }
相关文章:
- 我用C++做了一个计算器,但我对"type of calculator"的要求循环了两次。有人可以帮助指出我的错误吗?
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 两次相同的 for 循环:一个编译,另一个不编译
- while 循环在一个函数调用中执行两次
- C++ 为什么我不能使用循环:while(fin>>x) 两次
- 如何防止字符在 for 循环中打印两次?C++
- 做 同时循环重复 cout 线 每循环两次
- 在 for 循环(链表)中删除两次后,变量不可用
- C++ cout 打印两次在循环中做
- c++While循环打印couts两次
- 当循环应该只运行一次时,执行两次while循环(C++)
- 如何循环两次,将不同的值插入两个不同的堆栈
- c ++ 如何阻止我的循环两次吐出最后一个输入
- 当循环时,在c++中的cin.get()之前循环两次
- C++程序 尝试连续运行两次写入循环时显示".. stopped working"错误
- 通过两次链接同一个库来解决循环依赖关系
- 一旦用户错了两次,就结束循环
- 在循环重复两次之前,break 语句不起作用
- 为什么这个while循环在请求name之前执行两次
- 如何使用数组进行两次循环移位