| | |
Only accept an alphabetical character
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
I've just completed an exercise from a book wherein the task is to display a menu of choices each associated to an alphabetical character. The program is to reject invalid characters and only finishing when a valid choice is made. Below is my solution, it achieves the task but I'd like to know if there is a completely easier approach.
Any advice welcome.
C++ Syntax (Toggle Plain Text)
// chap05q03.cpp // C++ Primer Plus, Fifth Edition // Chapter 6, Page 276. // Programming Exercise # 3 // 4 Dec, 2007. #include <iostream> int main() { using namespace std; char ch; char msg[] = "\nPlease enter c, p, t or g: "; bool invalid = true; cout << "Please enter on of the following choices:\n\n"; cout << "c) carnivore p) pianist\n"; cout << "t) tree g) game\n"; while (invalid) { cin >> ch; if ((ch != 'c') && (ch != 'p') && (ch != 't') && (ch != 'g')) { cin.clear(); while (cin.get() != '\n') continue; cout << msg; } else invalid = false; // we've got a correct entry, exit loop. } switch (ch) { case 'c' : cout << "Option 'c' selected"; break; case 'p' : cout << "Option 'p' selectd"; break; case 't' : cout << "Option 't' selected"; break; case 'g' : cout << "Option 'g' selected"; break; default : cout << "It will never get her"; break; } system("PAUSE"); return 0; }
Any advice welcome.
You could put the switch inside the loop (better as a do...while), let the default case handle the erroneous inputs. What is your if( ) condition becomes the while( ) condition.
Val
Val
"We Americans got so tired of being thought of as dumb by the rest of the world that we went to the polls last November and removed all doubt."
~~~~~~~~~~~~~~~~~~
Looking for an exciting graduate degree? Robotics and Intelligent Autonomous Systems (RIAS) at SDSM&T See the program brochure here.
~~~~~~~~~~~~~~~~~~
Looking for an exciting graduate degree? Robotics and Intelligent Autonomous Systems (RIAS) at SDSM&T See the program brochure here.
•
•
•
•
You could put the switch inside the loop (better as a do...while), let the default case handle the erroneous inputs. What is your if( ) condition becomes the while( ) condition.
Val
C++ Syntax (Toggle Plain Text)
// chap05q03-a.cpp // C++ Primer Plus, Fifth Edition // Chapter 6, Page 276. // Programming Exercise # 3 // 4 Dec, 2007. // modified after advice from DaniWeb C++ forum. #include <iostream> int main() { using namespace std; char ch; char msg[] = "\nPlease enter c, p, t or g: "; bool invalid = false; cout << "Please enter on of the following choices:\n\n"; cout << "c) carnivore p) pianist\n"; cout << "t) tree g) game\n"; do { cin >> ch; invalid = false; switch (ch) { case 'c': cout << "Option 'c' selected\n"; break; case 'p': cout << "Option 'p' selectd\n"; break; case 't': cout << "Option 't' selected\n"; break; case 'g': cout << "Option 'g' selected\n"; break; default : cout << msg; cin.clear(); while (cin.get() != '\n') continue; invalid = true; } } while (invalid); system("PAUSE"); return 0; }
Last edited by superjacent; Dec 4th, 2007 at 3:41 am. Reason: Formatting was all out of whack.
You can also let 'c','p' & 't' fall through to 'g'
•
•
•
•
C++ Syntax (Toggle Plain Text)
switch (ch) { case 'c': case 'p': case 't': case 'g': cout << "Option '" << ch << "' selected\n"; break; default : cout << msg; cin.clear(); while (cin.get() != '\n') continue; invalid = true; }
•
•
•
•
Thanks for the advice, very much appreciated. I've altered the code as suggested and is a lot 'cleaner' looking.
By the way, what does
cin.clear(); do? You might want to look it up.Another thing to look at is
system("PAUSE"); See this The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
•
•
•
•
Not bad, although it's still not formatted properly.
By the way, what doescin.clear();do? You might want to look it up.
Another thing to look at issystem("PAUSE");See this
cin.clear() is that if the cin fails (eof or mismatch of data) then further access or use of cin is prevented; to avoid this use the clear() method.I guess you're probably suggesting that in this particular case it's not needed. Looking at the code I can't see how a mis-match of data
cin >> ch could occur and I don't think EOF is an issue either. I hope I haven't embarrassed myself with this answer or response.Taking this a step further in relation to cin.clear(). If the receiving variable is of a numeric type is that when cin.clear() would be considered in fixing up erroneous data entries.
•
•
•
•
My understanding re cin.clear() is that if the cin fails (eof or mismatch of data) then further access or use of cin is prevented; to avoid this use the clear() method. •
•
•
•
I guess you're probably suggesting that in this particular case it's not needed. Looking at the code I can't see how a mis-match of data cin >> ch could occur and I don't think EOF is an issue either. I hope I haven't embarrassed myself with this answer or response. •
•
•
•
Taking this a step further in relation to cin.clear(). If the receiving variable is of a numeric type is that when cin.clear() would be considered in fixing up erroneous data entries.
cin.clear() does is clear the error flags. If they were set, it does not fix any data entries. The way you're using it, the error is simply cleared and ignored. You never test for one, so you don't even know it happened.What you suggested above is "If the receiving variable is of a numeric type" and you type in a letter instead,
cin.clear() magically changes the letter to a digit. What in fact happens is the error flags are set, nothing is loaded into the variable (previous value remains unchanged), and the letter stays in the input stream for the next cin . The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
•
•
•
•
Actually, no. Allcin.clear()does is clear the error flags. If they were set, it does not fix any data entries. The way you're using it, the error is simply cleared and ignored. You never test for one, so you don't even know it happened.
What you suggested above is "If the receiving variable is of a numeric type" and you type in a letter instead,cin.clear()magically changes the letter to a digit. What in fact happens is the error flags are set, nothing is loaded into the variable (previous value remains unchanged), and the letter stays in the input stream for the nextcin.
Thanks for the advice, and everyone else as well, it's really helped.
![]() |
Similar Threads
Other Threads in the C++ Forum
- Previous Thread: Need Help with Address Book Assignment
- Next Thread: MCI (Multimedia Control Interface) in C++ HELP PLEASE!
| Thread Tools | Search this Thread |
api array based beginner binary bitmap c++ c/c++ calculator char char* class code coding compile compiler console conversion count database delete deploy desktop developer dll download dynamic dynamiccharacterarray email encryption error file forms fstream function functions game givemetehcodez google graph gui homeworkhelp homeworkhelper iamthwee ifstream input int java lib linkedlist linker list loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference rpg sorting string strings temperature template test text text-file tree unix url variable vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






