hi, I am just learning C++ ATM, but have programmed in other languages with moderate amounts of success (java, c#).
I am trying to validate input (cin) to an integer, but I want to refuse any non integer. unlike most other higher level (lazier I guess) languages c++ will somehow go about putting any value into an int; which cause all sort of problems.
what I want to do check the string to make sure it is an integer than parse it into an int.
this must be a common task surely, so there must be a function (that returns a bool? isInt - something like that), or at least what is the common way to do it. The best way I can think of would be to extract cin to char[] (or pointer***), then compare each element again '1', '2', '3'... then if all is well then parse. but there must a be a more elegant way. (like c#'s tryParse)
***secondary question 'bout pointers; when should I use them over arrays. (or am i viewing them wrong). Also when i make an istance of a class, which is better practice. (or when would you use each; bare in mind that all this was done for me in C# & java)
to make a pointer:
myclass *mcp = new myclass("constructor")
mc->method();
Don't forget about extra junk that may be at the end of the number:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int n;
// Instruct the user
std::cout << "Please enter an integer value> " << std::flush;
while (true)
{
// Get the user's input
std::string input;
std::getline(std::cin,input);
// Trim any trailing whitespace
input.erase(input.find_last_not_of(" \t")+1);
// Convert it to a number
std::istringstream stream(input);
stream >> n;
// Was conversion successful without any leftovers?
if (stream.eof()) break;
// Re-instruct the user
std::cout << "You must enter an INTEGER value> " << std::flush;
}
std::cout << "Good job! You entered the number \"" << n << "\".\n";