如何在C++中"q"用户输入时退出 do-while 循环

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

本文关键字:输入 退出 循环 do-while 用户 C++      更新时间:2023-10-16

如果用户按"q",我想退出循环,但是当我按q时,它会进入无限循环。我的 if 语句有什么问题?为什么当用户按"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");
} 

这个想法是:读取一个char(不是数字);看看它是否等于q。如果是,请退出。如果没有,请putback char,然后读取一个数字。

#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
        ...
    }
}

如果您希望用户键入exit或其他长度超过 1 个字节的内容,则此想法将不起作用。如果需要这么长的退出命令,则必须使用传统的解析机制(读取一行输入;将其与exit命令进行比较;如果不相等,则将字符串转换为数字)。