the problem I have here is: when I input an integer it works fine, but when i input any other thing, it doesn't give me a chance to input again when the loop iterates, it just keeps printing "error type the right thing" to the screen even though "cin var" is inside the loop.

#include<iostream>
#include<iomanip>
using namespace std;

int main(){
int var;

while(true){
    cout<<"please enter any integer"<<endl;
        cin>>var;
    if(cin.good()){
        cin.ignore(10, '\n');
        break;
    }
    cin.clear();
    cout<<"error, enter the right thing"<<endl;

}
return 0;}

Recommended Answers

All 3 Replies

cin.clear() resets the error flags, but does not empty the buffer, so next time round the loop, there's already something in the buffer.

You can use cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); to empty the buffer (requires #include <limits>). There are other options too.

This should work:

#include <iostream>

using namespace std;

int main()
{
  int var;
  cout << "please enter any integer" << endl;

  while(!(cin>>var))
    {
      cin.clear();
      cin.ignore(1000,'\n');
      cout << "Error, enter the right thing" << endl;
    }

  cout << "You entered: " << var << endl;

  return 0;
}

Enjoy :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.