gpt4 book ai didi

c++ - while 循环跳过行

转载 作者:行者123 更新时间:2023-11-30 00:45:58 24 4
gpt4 key购买 nike

我目前有这个功能:

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;
}

我将 DRYing 这段代码作为练习 ;)

关于c++ - while 循环跳过行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40760117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com