C++ 正在验证无字符和负输入的输入
我正在模拟一个计算器,想知道如何只接受正输入而不接受其他字符(负整数、字母表等) 我试过使用两个do while循环,一个验证正整数,另一个验证字符,但似乎一个输入不能有两个循环,否则看起来会很奇怪C++ 正在验证无字符和负输入的输入,c++,C++,我正在模拟一个计算器,想知道如何只接受正输入而不接受其他字符(负整数、字母表等) 我试过使用两个do while循环,一个验证正整数,另一个验证字符,但似乎一个输入不能有两个循环,否则看起来会很奇怪 do{ if (invalid == true) { cout << "Invalid input, please enter a positive number" << endl; } cout << "Please enter the fir
do{
if (invalid == true)
{
cout << "Invalid input, please enter a positive number" << endl;
}
cout << "Please enter the first number:" << endl;
cin >> num1;
cin.ignore();
invalid = true;
} while (num1 < 0);
invalid = false;
do{
if(无效==true)
{
cout我的建议是将整行读取为字符串(使用std::getline
),然后尝试将字符串解析为无符号整数
它可以像这样实现
unsigned value;
for (;;)
{
std::string input;
if (!std::getline(std::cin, input))
{
// Error reading input, possibly end-of-file
// This is usually considered a fatal error
exit(EXIT_FAILURE);
}
// Now parse the string into an unsigned integer
if (std::istringstream(input) >> value)
{
// All went okay, we now have an unsigned integer in the variable value
break; // Break out of the loop
}
// Could not parse the input
// TODO: Print error message and ask for input again
// Loop continues, reading input again...
}
这可以放在一个函数中进行泛化,因此可以重用它来获取多个值。您甚至可以将该函数作为模板,以便它可以用于不同的输入类型(有符号或无符号整数、浮点,甚至是具有适当输入运算符的对象>
重载)
比如说
#include <iostream>
#include <string>
int main()
{
int n;
for (;;) {
if (!(std::cin >> n)) {
// remove bad 'word'
std::cin.clear();
std::string s;
if (!(std::cin >> s)) {
std::cerr << "EOF" << std::endl;
return -1;
}
std::cerr << "not a number" << std::endl;
}
else if (n < 0)
std::cerr << "negative value" << std::endl;
else
break;
}
std::cout << "positive value " << n << std::endl;
return 0;
}
通常,在这些情况下,您希望读取字符串
,而不是像int
或double
那样的数值,并查看它是否匹配特定的数字模式。您可能对regex
感兴趣。可能的重复
pi@raspberrypi:~ $ g++ -pedantic -Wall -Wextra i.cc
pi@raspberrypi:~ $ ./a.out
aze
not a number
-1
negative value
2
positive value 2
pi@raspberrypi:~ $
pi@raspberrypi:~ $ echo | ./a.out
EOF
pi@raspberrypi:~ $ ./a.out
aze -1 23
not a number
negative value
positive value 23