Terminating a loop with q command

OK, so for our assignment we are asked to make a loop where it continues to prompt the user for an unsigned long long. After they give their number, a table is displayed, and after the table of text, the user is reprompted for a new value. If they want to quit, they have to use 'q' or 'Q'. If they input a different letter, an error message should occur. So, the only way I made it quit was by using a cin.fail() statement, but that doesn't work because any letter that is put will exit the program. I tried using if statements with the "value == 'q' or 'Q'" but it doesn't seem to work since the variable is an unsigned long long. Any ideas on how to fix this problem?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;

//displays table
void display(unsigned long long choice)
{
   cout << "TABLE";
}

//runs program
int main()
{
   unsigned long long value = 0;
   cout << "\nEnter a number (q to quit): ";
   cin >> value;
   if (cin.fail())
      return 0;
   else
   {
      while (!cin.fail())
      {
         display(value);
         cin.clear();
         cin.ignore();
         cout << "\nEnter a number (q to quit): ";
         cin >> value;
         if ((char)value == 'q' || (char)value == 'Q')
            return 0;
       }
   }
   return 0;
}
Last edited on
Why don't you read input as a string and try converting that to a number? If it fails, check if it is Q, and if not, print an error message.
Could you give me an example? Not sure how that would work. (The 'if it fails' part also kind of confuses me. How would it check to see if it failed?)
Start here:
http://www.cplusplus.com/articles/D9j2Nwbp/
Look at the stringstream part and see what you come up with.
Topic archived. No new replies allowed.