循环跳过线
While loop skips line
本文关键字:循环 更新时间:2023-10-16
我当前具有此功能:
double GrabNumber() {
double x;
cin >> x;
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << "You can only type numbers!nEnter the number: ";
cin >> x;
}
return x;
}
其目的是检查x
是否是有效的数字,如果不是有效的,则将其返回或重复cin >> x
(如果不是)。
在此功能期间称为:
void addition() {
cout << "nEnter the first number: ";
double a = GrabNumber();
cout << "Enter the second number: ";
double b = GrabNumber();
// rest of code
当我键入例如" 6 "时,当它告诉我输入第一个数字时,它接受它,但立即转到第二行,称其为错误,我什至没有输入输入。
我认为这是因为第一个输入仅接受" 6",而" "转到第二个输入返回错误。因此,while
的参数必须存在问题。
如果您的输入立即成功,则不会忽略该行的其余部分,最终将进入下一个输入。可以通过简单地复制cin.ignore
调用来解决。
double GrabNumber() {
double x;
cin >> x;
cin.ignore(numeric_limits<streamsize>::max(), 'n'); // <--
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << "You can only type numbers!nEnter the number: ";
cin >> x;
}
return x;
}
我将把此代码干燥作为练习;)
要避免这种问题,请使用getline
和stod
:
double GrabNumber() {
double x;
bool ok = false;
do
{
std::string raw;
std::getline (std::cin, raw);
try
{
x = stod(raw);
ok = true;
}
catch(...)
{}
} while(!ok);
return x;
}
在通常的情况下,使用getline
获取原始字符串并在此之后解析更容易。这样,您可以检查所有想要的内容:字符数,签名位置,如果只有数字字符,等。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 在循环C++中指定字符串之后,不会打印该字符串