Adam Zhu Adam Zhu - 2 months ago 11
C++ Question

about while (!(cin>>x))

Why do I have to input the number twice when I run the program below?

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int x;
int number;

cout << "Please enter a integer ." << endl;
cin >> number;

while (!(cin>>x))
{
cout << "Invalid value !" << endl;
system("pause");
return 0;
}

cout << "Your number is " << number << " ." << endl

Answer

You use

cin >> number;

And then

   while (!(cin>>x)) 

Both of which read a number.

Comments