"xeys_00" writes:
I'm trying to use the character "q" to exit this program. But if
anything but q is input , I want the loop to continue. Am I using the
wrong loop?
<snip>
The choice of a do-while loop is good. Your program seems to work OK as
long as the user follows the rules. If he types a letter when your program
expects a number you can have big problems. You can spend an inordinate
amouint of time trying to make even a simple thing such as this foolproof.
You violate one rule of good design, you introduce global variables, the
ones declared before main(). Here is a cut at a somewhat better version but
it is still not bulletproof. If the user enters two letters instead of one
when asked for a 'q", an upper case 'Q' thinking he can quit, enters much
too large a number when asked for a number, or enters a negative number, it
will still have problems.
----------------------
#include <iostream>
#include <string>
using namespace std;
int get_int()
{
int n;
do
{
cin >> n;
if(cin.fail())
{
cin.clear(); // clear the fail state
cin.ignore(1000, '\n'); // empty the buffer
cout << "Digits only\n";
}
else
return n;
}while(1);
}
//=======================
int main()
{
string fn = "John Smith";
int last_ix = fn.length() - 1;
char quit;
do
{
cout << "Which character?\n";
int n = get_int();
while(n > last_ix)
{
cout << "maximum index is " << last_ix << endl;
n = get_int();
}
cout << "Character selected is " << fn[n] << endl;
cout << "Press 'q' to quit\n";
cin >> quit;
} while(quit != 'q');
cin.get();
}