问题
In order to learn C++, I'm translating a program I wrote in Python.
I wrote this
n = 0
while n < 2:
try:
n = int(raw_input('Please insert an integer bigger than 1: '))
except ValueError:
print 'ERROR!'
in order to get an integer bigger than 1 from the user.
This is what I wrote in C++ for the moment:
int n = 0;
while (n < 2) {
cout << "Please insert an integer bigger than 1: ";
cin >> n;
}
I took a look at try-catch and it seems pretty straight forward. My concern is about how to check the input is an integer. I read about cin.fail() but I couldn't find any official document and I didn't really get how it works.
So, how can I check if the input is integer?
More in general, how can I check if the input is "anything"?
回答1:
For a situation like this, you'd probably want to read the input as a string, then inspect the string (e.g., "contains only digits, up to a maximum of N digits"). If and only if it passes inspection, parse an int out of it.
It's also possible to combine the inspection and conversion--for example, Boost lexical_cast<int>(your_string) will attempt to parse an int out of the string, and throw an exception if it can't convert the whole thing to an int.
回答2:
Your Python can code be translated more directly if you use C++11's std::stoi combined with std::getline to read a whole line of input. This is much easier than struggling with standard I/O error handling, which arguably does not have a very user-friendly interface.
std::stoi throws std::invalid_argument if the input could not be correctly parsed as an integer number, and std::out_of_range if the number is too small or too big to fit in an int.
#include <iostream>
#include <string>
int main() {
int n = 0;
while (n < 2) {
std::cout << "Please insert an integer bigger than 1: ";
std::string input;
std::getline(std::cin, input);
try {
n = std::stoi(input);
} catch (std::exception const&) {
std::cerr << "ERROR!\n";
}
}
}
If you want to make the code even more similar to its Python equivalent, then you can encapsulate the input in a function:
#include <iostream>
#include <string>
int raw_input(std::string const& message)
{
std::cout << message;
std::string input;
std::getline(std::cin, input);
return std::stoi(input);
}
int main() {
int n = 0;
while (n < 2) {
try {
n = raw_input("Please insert an integer bigger than 1: ");
} catch (std::exception const&) {
std::cout << "ERROR!\n";
}
}
}
来源:https://stackoverflow.com/questions/35299101/check-if-input-is-integer