0

I am confused about this. For example

#include <iostream>
int main(){
    using namespace std;
    int x, y;
    cout << "enter a number: \n";
    cin >> x
    if (x != ){                             // If user inputs anything besides a number, Program will then exit
    cout << "invalid";
    }
  return 0;
  }

what code could i use so that if the user decided to input a letter instead of a number, the program will then output invalid and the program will then exit

GG Bro
  • 65
  • 9
  • You need to check the status of the stream itself. I recommend [this `std::istream` reference](https://en.cppreference.com/w/cpp/io/basic_istream), and of course that you take some time going through your text book for hints. – Some programmer dude Oct 12 '19 at 07:56
  • `if (!cin)` ... – rustyx Oct 12 '19 at 07:58
  • @seccpur im still new at c++, never knew that such a small thing could be so deeply complicated. – GG Bro Oct 12 '19 at 08:16

1 Answers1

0

The operator >> used in combination with cin returns a reference that can be checked to see if the task of assigning the entry to the integer x was successful. If the operation has failed, meaning that the entry was not an integer, it returns a null pointer. In that case !(cin >> x) evaluates to true.

#include <iostream>
#include <cstdlib> // for exit()
using namespace std;
int main(){     
  int x;
  cout << "enter a number: \n";
  if (!(cin >> x) ){// If user inputs anything besides a number, Program will then exit
    cout << "invalid entry.\n";
    exit(0);
  }
  cout << "you entered number: " << x << endl;
  return 0;
}

See also, e.g., the answers to this question for more information.

Edit:

As an equivalent alternative one can also use cin.fail(). This results in a code that is more easily readable:

cout << "enter a number: \n";
cin >> x ;
if (cin.fail()){
 ...
}
RHertel
  • 23,412
  • 5
  • 38
  • 64
  • Thanks you so much, I've been staring at my code for almost 2 hours now and i just couldn't seem to figure it out. – GG Bro Oct 12 '19 at 08:26