Originally Posted by
aaleclaire
Could someone please recommend a good way to safely get input from the command line, check it type correctness, and throw away extra data?
The way I recommend is to read the line into a string, then parse the string to extract the specific input. This way, you don't need to "throw away extra data" because the next read will read the next line, rather than whatever is left on the line. This also avoids the problem where you read into an int, then try to read the next line into a string, only to find that you read nothing into the string because you ended up reading the rest of the previous line instead of the next line.
Unfortunately, doing this, while simple, requires more stuff that you probably don't know, unlike manasij7479's suggestion, e.g.,
Code:
// Headers to include
#include <iostream>
#include <string>
#include <sstream>
// Read a line from standard input.
std::string line;
std::getline(std::cin, line);
// Create an input string stream from the line to extract the int
std::istringstream ss(line);
int my_int;
if ((ss >> my_int) && ss.eof())
{
// Use my_int
}
else
{
// Could not extract the int, or there was invalid input after extraction.
}