while 循环跳过行
While loop skips line
我目前有这个功能:
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;
}
我将 DRY 这段代码作为练习 ;)
为避免此类问题,建议使用 getline
and 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
获取原始字符串并在之后解析它会更容易。这样,你可以检查你想要的一切:字符数,符号位置,如果只有数字字符,等
我目前有这个功能:
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;
}
我将 DRY 这段代码作为练习 ;)
为避免此类问题,建议使用 getline
and 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
获取原始字符串并在之后解析它会更容易。这样,你可以检查你想要的一切:字符数,符号位置,如果只有数字字符,等