首页 > 解决方案 > 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!";
}

标签: c++

解决方案


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.


推荐阅读