alright so in my program, the user is prompted 3 times to enter an integer value. my problem is, i don't know how to make it so that if the user inputs say a letter for instance, the program won't screw up. is there a way i can avoid that?
alright so in my program, the user is prompted 3 times to enter an integer value. my problem is, i don't know how to make it so that if the user inputs say a letter for instance, the program won't screw up. is there a way i can avoid that?
Use fgets() to read the input as a string, then validate and convert it.
What i/o lib do you use?
Learn C++ (C++ Books, C Books, FAQ, Forum Search)
Code painter latest version on sourceforge DOWNLOAD NOW!
Download FSB Data Integrity Tester.
Siavosh K C
i use iostream.h.
ok so the program is simple: to calculate percentages of the gross profit of a movie company. the user is supposed to input the amount of tickets sold for seniors, adults and juniors. i have the program working properly, but i want to make it so that if the user inputs a letter or something instead of a number for the amount of tickets sold that the program will say "please enter a number" or something along those lines and then prompt the user again.
You have the
After that write thisCode:cin>>integer;
Code:if(cin.fail()) { cin.clear(); cin.ignore(500,'\n'); //Asking for integer again, etc. }
Last edited by siavoshkc; 01-24-2006 at 10:21 AM.
Learn C++ (C++ Books, C Books, FAQ, Forum Search)
Code painter latest version on sourceforge DOWNLOAD NOW!
Download FSB Data Integrity Tester.
Siavosh K C
>> i use iostream.h.
That is an old, non-standard header that doesn't work on many modern compilers. Consider using iostream instead.
Either way, siavoshkc's code is good, although I would make it a while loop and place the read directly into the control: while (!(cin >> integer)). That way it will keep prompting for a number until a number is pressed.
Daved, you mean this?
Code:using namespace std; #include <iostream>
Learn C++ (C++ Books, C Books, FAQ, Forum Search)
Code painter latest version on sourceforge DOWNLOAD NOW!
Download FSB Data Integrity Tester.
Siavosh K C
I meant <iostream> like you have it, yes. You would normally put the using directive after the #include, and of course you don't need the using directive if you add std:: to the name of the stuff from the standard library (which is how I prefer to do it).
alright so i used the cin.ignore and it's better now because it doesn't give a random value anymore, but now i need it to reprompt the user instead of just skipping the prompt and going to the next.
>> now i need it to reprompt the user instead of just skipping the prompt and going to the next.
See my first post above. Use the read as the control of a while loop.Code:while (!(cin >> integer)) { cin.clear(); cin.ignore(500,'\n'); // Re-prompt here. }