-3

I want to exit the loop if the user presses "q" but when I press q, it goes into an infinite loop. What is wrong with my if statement? Why does it not recognize when the user presses "q"?

#include<iostream>
using namespace std;

int main()
{
string user_input;
double price;
do
{
    cin >> price;
    int multiple = price * 100;
    if (user_input == "q")
    {
        break;
    }
    else if (multiple % 5 == 0)
    {
        cout << "This is a multiple of 0.05" << endl;
        return 1;
    }
    else
    {
        cout << "No multiple" << endl;
    }
} while (1 || user_input != "q");
system("pause");
} 
Ian Vasco
  • 1,280
  • 13
  • 17
John Doe
  • 9
  • 1
  • 3

1 Answers1

1

The idea is: read a char (not a number); see if it is equal to q. If yes, quit. If not, putback the char and then read a number.

#include<iostream>
using namespace std;

int main()
{
    char user_input; // note: changed it from string to char
    double price;
    while (true) // infinite loop; exit conditions are inside the loop
    {
        cin >> ws >> user_input; // note: it's important to discard whitespace

        if (user_input == 'q') // note: changed from " to '
            break;

        // Note: for putback to succeed, it must be only 1 byte, cannot be a string
        cin.putback(user_input);

        if (!(cin >> price))
            break; // note: exit on error

        // Your code here
        ...

    }
}

This idea will not work if you want the user to type exit or something else longer than 1 byte. If you need such a long exit command, you must use a traditional parsing mechanism (read a line of input; compare it with exit command; if not equal, convert the string to a number).

anatolyg
  • 26,506
  • 9
  • 60
  • 134