| | |
Only accept an alphabetical character
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
•
•
•
•
the code actually has a bug, for example you've entered something like this: c2,
the program will behave unexpectedly, how to remedy this?
ch needs to be checked prior to the switch statement. I've modified my original program that I posted at the top of this thread. What needed to be done is simply make sure that the next character was a newline, if it was then only a single character was input. If the next character wasn't a newline then something like c2 was entered.Here's the code:
cpp Syntax (Toggle Plain Text)
// chap06q03.cpp // C++ Primer Plus, Fifth Edition // Chapter 6, Page 276. // Programming Exercise # 3 // 4 Dec, 2007. // 15 Apr, 2008 - modified - disregarding c2 etc. #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')) { while (cin.get() != '\n') continue; cout << msg; } else if (cin.get() == '\n') invalid = false; else { while (cin.get() != '\n') continue; cout << msg; } } 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; } // exit routine cout << "\n\n...Press ENTER to Exit System..."; cin.get(); return 0; }
![]() |
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 arrays based beginner binary bitmap c++ c/c++ calculator char char* class classes code coding compile compiler console conversion convert count data database delete deploy developer dll download dynamiccharacterarray email encryption error file forms fstream function functions game generator getline givemetehcodez graph gui homeworkhelp homeworkhelper iamthwee ifstream input int java lib 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 text text-file tree url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets





