0

First of all I know the question title is not clear, thus, let me explain my issue.

I am writing a cpp code where I use std::cin, it is supposed to check if the input is or is not a number and if it is negative or positive.

Here is my code:

#include <windows.h>
#include <iostream>

using namespace std;

int main(void) {
    SetConsoleTitle(" ");
    while(true) {
        int x;
        if((cin >> x)) {
            cin.ignore();
            if(x > 0) {
                cout << "Podmienka splnena\n";
            }else{
                cout << "Podmienka nesplnena\n";
            }   
        }else{
            cin.ignore();
            cout << "Neplatny vstup\n";
        }
    }
}

The issue I am having is that it seems that cin does not accept any new input in case the input was not a number, which is pretty odd, what happens is that it will keep going on and on with the previous input, I hope I was pretty clear.

Arty
  • 45
  • 6

2 Answers2

1

When input fails, cin enter a failed state (can be tested by cin.fail()). After removing the bad input, you need to call cin.clear() to reset the state.

BoP
  • 2,310
  • 1
  • 15
  • 24
  • Thanks, this is exactly what I have been looking for, I have tried some of those functions (cin.ignore() and cin.clear()) but I was not aware they had to be used together and In a specific order – Arty Dec 02 '21 at 10:19
  • Note that you should call `cin.clear()` *before* calling `cin.ignore()` ... and you don't need to call the `ignore` after a successful read. – Adrian Mole Dec 02 '21 at 10:20
1

The problem is the you don't clear the failbit from the stream. This can be done with the clear function. So the correct way would be:

else{
           
        cout << "Neplatny vstup\n";
        cin.clear();//clear the error flag
        cin.ignore();
        }

Alternative Solution

Note that you can also do this without using cin.ignore, cin.ignore as shown below. The below example takes the input as std::string and then does the validation.


#include <iostream>
#include <string>
#include <sstream>

int main(void) {
    std::string input;
    int x;
    while(std::getline(std::cin,input)) {
        std::istringstream ss(input);
        if((ss >> x)) {
          
            if(x > 0) {
                std::cout << "Podmienka splnena\n";
            }else{
                std::cout << "Podmienka nesplnena\n";
            }   
        }else{
           
            std::cout << "Neplatny vstup\n";
             
        }
    }
}
Jason
  • 36,170
  • 5
  • 26
  • 60