c++ - How to input a character into an int without breaking the console and giving an error message?
问题描述
I want to ask the user to enter an int
value, and if they enter anything else then it will give them an error message and let them retry. I have that part figured out, but now when the user is to enter an int
value, it will make them enter it twice. Does anyone know why this happens?
#include <iostream>
using namespace std;
int main() {
int i;
char x;
RETRY:
cout << "Please enter a number: ";
cin >> i;
if(!(cin >> i)){
cin.clear();
cin.ignore(10000, '\n');
cout << "ERROR! ENTER A NUMBER!" << endl;
cout << "Enter any character to continue: ";
cin >> x;
system("clear");
goto RETRY;
}
cout << "Successful!";
}
解决方案
You are asking for an integer twice.
cin >> i; // the 1st query here
if(!(cin >> i)){ // the 2nd query here
You should remove cin >> i;
before the if
statement.
推荐阅读
- image - Alchemy CMS - Cloudinary - 站点 - 为每个站点使用 diff 文件夹 - 未过滤站点的图像
- c# - 共享会话状态不起作用;两个 ASP.NET_SessionId cookie?
- gitkraken - 我只能在树视图中查看本地或远程分支吗?
- django - Django Web 应用程序的 Heroku 错误请求服务器错误 500
- javascript - 如何让我的选择框和地图脚本说话
- php - mysqliquery 上的 PHP MYSQL INT 0
- vue.js - ApexCharts 如何动态更新 y 轴刻度?
- c - C - 使用浮点数作为循环计数器
- python - 在for循环中合并dict
- javascript - 使用纯 javascript 通过选中单选按钮取消选中复选框