It is still not okay.
When the input is a number preceded by any character like 123asds, it will assign 123 to getYear instead of outputting Invalid Input.
What will I add to this code?
cin.ignore(numeric_limits<streamsize>::max(),'\n');
or should I use sstream?
#include <cstdio>
#include <ctype.h>
#include <string.h> // or is it <cstring> ?
int main()
{
char year[80]; /* Could be 4+1 but from what I'm guessing you want to get the complete "123asds" as it is, so, 80 should be enough? */
size_t len;
bool strIsNumber(char *);
cout << "Enter year: ";
fgets(year, 80, stdin);
len = strlen(year);
if(strIsNumber(year) && len <= 4) {
/* Do what you will with a valid input here
... */
} else {
cout << "Invalid input!\n"; // print error message
}
return 0;
}
bool strIsNumber(char *buff)
{
int mybool;
while(mybool=isdigit(*buff++)) ;
return mybool ? 1 : 0;
}
That is the only way of getting all what the user enters.
If you want a pure integer then after performing the check use the library function int atoi(char *). The return value is the converted integer - use that.
Don't forget to #include<cstdlib> if you use it.
EDIT: Sorry about the includes. I'm more used to the C header files.
-unoriginal