如何在C++中"q"用户输入时退出 do-while 循环
How to exit do-while loop when user input is "q" in C++
如果用户按"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
命令进行比较;如果不相等,则将字符串转换为数字)。
相关文章:
- C++逗号分隔的输入数组代码过早退出
- 程序在接受输入后退出
- 如何实现否定用户输入退出程序和打印列表?
- 程序在没有输入的情况下退出,它有基本的,驱动的类属性初始化问题
- C++中的奇怪异常代码,当用户输入为 23 时,退出值 1,073,740,940(代码:0xc0000374)
- C++:如果用户输入数字将其转换为单词,并且如果按回车键程序应退出,则使用开关大小写
- 为什么在接受输入后循环退出时不会这样做
- C++:为什么当我想输入"q"退出时,这会给我一个异常抛出错误?
- 退出循环,除非未给出输入
- 使用ENUM输入和退出菜单,然后切换SFML
- 在C++测试家庭作业问题中的字符串输入时无法退出循环(作为数据验证)
- 使用输入重载时,是否可以像这样退出 while 循环
- 虽然循环在执行名称输入时过早退出
- 如何在C++中"q"用户输入时退出 do-while 循环
- 我想让程序保持运行,直到用户输入 n 退出程序
- 如果退出数组,请从另一侧输入
- 我找不到第一个用户输入后立即退出程序的原因
- 为什么当我尝试输入"x"退出程序时出现分段错误
- 保持运行程序,直到用户输入退出
- 在c++中使用函数中的用户输入退出程序