Read a whole line from std::cin
into a std::string
with std::getline
, then convert the line to an integer number with a std::istringstream
. Finally, after the conversion, check if there are characters left in the string stream. Here's a complete example:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string line;
std::getline(std::cin, line);
std::istringstream is(line);
int number;
is >> number;
if (is)
{
if (!is.eof())
{
std::cerr << "input does not end with a number\n";
}
else
{
std::cout << "input ok\n";
}
}
else
{
std::cerr << "inut does not start with a number or is too big for an int\n";
}
}