-3

My C++ program needs to ask the user to input two values. In order to avoid non-integer values, I wanted to create a loop like this:

#include <iostream>
using namespace std;

int main(){
     int x,y;

     while ((typeof(x)!=int){
         cin>>x;
         cin>>y;
     }
     return 0;
}

However, it does not work. Does anyone know how to do it?

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    That may be what you want to do, but completely wrong on how you actually accomplish this. Type association is a compile-time thing, not a runtime thing. If you're expecting an `int` , then you should try to read an `int`. If it works, great. if it didn't, you clean up whatever is left in the input stream, reset the stream state, and try again (usually after prompting the user of the error of their ways). – WhozCraig Jun 02 '20 at 02:50
  • "it does not work" is not a sufficiently detailed diagnostic. What, _specifically_ is the problem? – tadman Jun 02 '20 at 02:56
  • In C++, a data type needs to be known at compile time. – Omid Jun 02 '20 at 03:08
  • `int x,y;` makes `x` an `int`. Nothing can change that. You need to test `cin>>x;` It will fail if the user did not provide an `int`. If it fails, you need to clean up by `clear`ing the error flag and removing the non-`int` from `cin` before continuing. – user4581301 Jun 02 '20 at 03:39

1 Answers1

0

You can't evaluate any datatype directly as an expression.

Use std::cin.good() (returns boolean) for verification if the number(s) entered were integer.

int val1, val2;

std::cout << "Input two integers: ";
std::cin >> val1 >> val2;

while (!std::cin.good()) {
    std::cin.clear();
    std::cin.ignore(INT_MAX, '\n');

    std::cout << "Incorrect! Input two integers: ";
    std::cin >> val1 >> val2;
}

std::cout << val1 << ' ' << val2;

Sample Output

Input two integers: 33 h
Incorrect! Input two integers: l h
Incorrect! Input two integers: 1 2
1 2
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34