-
variable types
So, here's my problem, I take input, it's necessary that the input is an int
when you try to put in a char through cin>> the while loop doesn't evaluate correctly and an endless loop starts
the input is being returned through a seperate function
if I can tell whether or not cin>> is returning an int within my function, then I can set up protocols against the endless loop
trouble is I have no clue how to find out what type of variable is coming in through cin
any tips?
-
The quick answer is don't read numbers. Read a string, and then use the isdigit() and atoi() functions to check if it is valid numerical input, and then convert it to an int.
You'll need the <ctype> header for isdigit, but I don't remember where atoi is. Let me check though...
EDIT: okay, atoi is in <cstdlib>.
Unless there's a function I'm missing, you do have a bit of coding.
You'd likely want to make a string, and cin to that. Then loop through the string, checking if each element is a number using isdigit. That's where you input-checking will happen. Then, if you want to use the number, turn the string into a c-string, and use the atoi function to get it into an int.
Although now that I think of it, there must be a function that checks if a string is a number, as it would need to handle things like different bases and decimals. Hopefully one of the more experienced forum-dwellers could shed some light on that.
-
>I have no clue how to find out what type of variable is coming in through cin
The type of the variable you give it is the type it expects. So if you want an int, but you still want to protect against invalid characters, you need to either read all input as a string and parse, or do something like this:
Code:
while (!(cin>> number)) {
cerr<<"Invalid input, please try again: ";
cin.clear();
cin.ignore(256, '\n');
}
Further details can be found in the FAQ for both reading numbers and reading lines.