the code actually has a bug, for example you've entered something like this: c2,
the program will behave unexpectedly, how to remedy this?
Good pick up. It appears that the variable
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:
// 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;
}
Given some time I'm sure the above program can be smoothed out, but at least it demonstrates only accepting a single character (not using strings and other methods). As it stands now, clearly there are a couple of snippets which are candidates to be functions.
Reputation Points: 11
Solved Threads: 3
Junior Poster in Training
Offline 66 posts
since Nov 2007