I’m admittedly not the most experienced with C++, but am surprised to be having issues with getting such a simple function to work properly. All I’m wanting is a function to get a user’s input and ensure it obtains an integer(without crashing due to unexpected input) and then return that value to the calling function. It should not accept any special characters or spaces whatsoever. Essentially, I want it to be just like the Java equivalent that I’ll post below:
public static int getInt()
{
boolean isNum = false; //test variable
String str; //to hold input
do
{
str = keyboard.nextLine();
if (!(isNum = str.matches("\\d+")))
{
System.out.println("Enter a valid whole number, try again.");
}
} while(!isNum);
return Integer.parseInt(str);
}
You just try to read an
intwithcin >> [int variable], and make sure it succeeded. If not, wash, rinse, and repeat:That will work, but will return
12when given input likebecause it will read the 12 and stop at
a. If you do not want to just “get as much as you can” and want to read the whole line (which is what the Java snippet apparently does) then you can usestd::getlineand try to convert the resulting string into an integer withstd::stoi:That way will not return on input like
because it will try to convert the entire line
143 bbcto an integer and tell the user to try again becausebbccan’t be converted to an integer. It will only return when the entire line is integer input.You can actually accomplish this by using regexen like the Java example does, but I think it’s a waste to pull out regexes for this simple task.
Edit:
If you want to reject decimal input instead of truncating it, you can convert the input to a
doubleand check to make sure it doesn’t have a decimal part: