C++ - cin 只取一个整数
C++ - cin to only take one integer
如果我输入的不是数字,此代码可以正常工作,例如F
:它会打印错误信息。但是,如果我输入例如2F2
or ,它将接受 2
并通过检查,继续我的代码并在下一个 cin >>
语句中将 F
放入,然后循环返回并将 2
放入
我该怎么做才能让它只接受一个数字,例如2
而不是例如2F2
或 2.2
?
int bet = 0;
// User input for bet
cout << " Place your bet: ";
cin >> bet;
cout <<
// Check if the bet is a number
if (!cin.good())
{
cin.clear();
cin.ignore();
cout << endl << "Please enter a valid number" << endl;
return;
}
bool Checknum(std::string line) {
bool isnum = true;
int decimalpoint = 0;
for (unsigned int i = 0; i < line.length(); ++i) {
if (isdigit(line[i]) == false) {
if (line[i] == '.') {
++decimalpoint; // Checks if the input has a decimal point that is causing the error.
}
else {
isnum = false;
break;
}
}
}
if (decimalpoint > 1) // If it has more than one decimal point.
isnum = false;
return isnum;
}
如果您从用户那里获取字符串,这应该可以。您可以将字符串转换为整数或浮点数(分别为 stoi 或 stof)。它可能不是最好的解决方案,但这就是我所拥有的。请原谅缩进。
- 执行
getline
从 cin
读取一整行输入。
- 创建一个
stringstream
来解析你得到的字符串。
- 在此解析器中,读取数字;如果失败 - 错误
- 读取空格;如果它没有到达字符串的末尾 - error
#include <sstream>
...
int bet = 0;
std::cout << " Place your bet: ";
while (true)
{
std::string temp_str;
std::getline(cin, temp_str);
std::stringstream parser(temp_str);
if (parser >> bet && (parser >> std::ws).eof())
break; // success
cout << endl << "Please enter a valid number" << endl;
}
此代码会一直打印错误消息,直到收到有效输入。不确定这是否正是您想要的,但这很常见 UI.
这里>> ws
表示"read all the whitespace"。而 eof
("end of file") 表示 "end of the input string".
如果我输入的不是数字,此代码可以正常工作,例如F
:它会打印错误信息。但是,如果我输入例如2F2
or ,它将接受 2
并通过检查,继续我的代码并在下一个 cin >>
语句中将 F
放入,然后循环返回并将 2
放入
我该怎么做才能让它只接受一个数字,例如2
而不是例如2F2
或 2.2
?
int bet = 0;
// User input for bet
cout << " Place your bet: ";
cin >> bet;
cout <<
// Check if the bet is a number
if (!cin.good())
{
cin.clear();
cin.ignore();
cout << endl << "Please enter a valid number" << endl;
return;
}
bool Checknum(std::string line) {
bool isnum = true;
int decimalpoint = 0;
for (unsigned int i = 0; i < line.length(); ++i) {
if (isdigit(line[i]) == false) {
if (line[i] == '.') {
++decimalpoint; // Checks if the input has a decimal point that is causing the error.
}
else {
isnum = false;
break;
}
}
}
if (decimalpoint > 1) // If it has more than one decimal point.
isnum = false;
return isnum;
}
如果您从用户那里获取字符串,这应该可以。您可以将字符串转换为整数或浮点数(分别为 stoi 或 stof)。它可能不是最好的解决方案,但这就是我所拥有的。请原谅缩进。
- 执行
getline
从cin
读取一整行输入。 - 创建一个
stringstream
来解析你得到的字符串。 - 在此解析器中,读取数字;如果失败 - 错误
- 读取空格;如果它没有到达字符串的末尾 - error
#include <sstream>
...
int bet = 0;
std::cout << " Place your bet: ";
while (true)
{
std::string temp_str;
std::getline(cin, temp_str);
std::stringstream parser(temp_str);
if (parser >> bet && (parser >> std::ws).eof())
break; // success
cout << endl << "Please enter a valid number" << endl;
}
此代码会一直打印错误消息,直到收到有效输入。不确定这是否正是您想要的,但这很常见 UI.
这里>> ws
表示"read all the whitespace"。而 eof
("end of file") 表示 "end of the input string".