Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Is there anyway in c++ that I can use an "if" to see if a variable is a of a specific type?
Ok so the basic idea is that I want to use an if so i can output an message that tells the user that the type he just inputted is a wrong type I did something like this:
int n;
cout<<"how many names do you want to register"<<endl;
cin>>n;
if (n != int) {
cout<<"Please input an integer value"
}
I understand that I will have to put some sort of loop but I hope this gets the idea out, I want to do this because I see a lot of people making mistakes with the type..
please help and thanks!
2 Answers
- ?Lv 710 years agoFavorite Answer
Yes there is a way to use an "if" to see if an object has a specific type, but in your case the type of n is int (you've defined it that way!), and such test will always be true.
If the user attempts to input something that is not an int, the line "cin >> n;" will not write anything into n; it will set the stream error flags instead. That's what you have to test with your if:
int n;
cout<<"how many names do you want to register"<<endl;
cin>>n;
if (!cin) {
cin.clear(); // unset the error flag
cin.ignore( numeric_limits<streamsize>::max(), '\n'); // get rid of the bad input
cout<<"Please input an integer value";
}
test: https://ideone.com/56hIU
- green meklarLv 710 years ago
Input into a char array, then parse the char array to check whether it's a valid integer, and convert it using atoi() if it is valid.
Note that completely safe input to a char array is actually surprisingly difficult. However, if you operate under the assumption that inputs will not exceed a certain relatively small length, it makes it much simpler.