简体   繁体   中英

How to exit do-while loop when user input is "q" in C++

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");
} 

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM