user2054823
user2054823

Reputation: 23

Cin.clear() issue

Im writing a program that is supposed to accept integers only, I'm currently using

int x;
cin >> x;
while(cin.fail()){
    cout << "error, please enter an integer" << endl;
    cin.clear();
    cin.ignore();
    cin >> z;
    cout << "you entered" << z << endl;
}

however if i enter a double for example 1.2 the program ignores the decimal point but sets the value of z to 2 and doesnt request user input. What can i do to stop this?

Upvotes: 0

Views: 141

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476970

Before this goes out of hand, here's once again a typical example of an input operation:

#include <string>   // for std::getline
#include <iostream> // for std::cin
#include <sstream>  // for std::istringstream


for (std::string line; std::cout << "Please enter an integer:" &&
                       std::getline(std::cin, line); )
{
    int n;
    std::istringstream iss(line);

    if (!(iss >> n >> std::ws) || iss.get() != EOF)
    {
        std::cout << "Sorry, that did not make sense. Try again.\n";
    }
    else
    {
        std::cout << "Thank you. You said " << n << ".\n";
    }
}

It will keep asking you for integers until you close the input stream or terminate it in some other way (e.g. by typing Ctrl-D).

You will find hundreds, if not thousands, of variations on this theme on this website.

Upvotes: 4

Related Questions