Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined behaviour when entering `char` for integer variable with `std::cin`

Tags:

c++

I have this while loop, just to check if the entered number is 2. If the user entered by accident a letter instead of a number the loop goes to infinity even though I've added isdigit, but didn't fix the loop from going crazy if the input is a character. This is code:

int num1;
bool cond {false};
while(!cond){
    cout<<"enter 2:";
    cin>>num1;
    if (!isdigit(num1)){
        cout<<"not a digit:";
        cin>>num1;
    }
    //
    if(num1 == 2)
        cond = true;
}
like image 513
zizou Avatar asked Apr 21 '26 06:04

zizou


2 Answers

I would suggest trying something a little more straightforward instead of your current code:

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

int main()
{
   int num1;
   cout << "Please enter the number 2:";
   cin >> num1;
   while (num1 != 2)
   {
       cin.clear(); //Clears the error flag on cin. 
       cin.ignore(numeric_limits<streamsize>::max(), '\n');
       cout << "You did not enter the number 2, Please try again:";
       cin >> num1;
   }
   
   return 0;

}

Now, cin.ignore(numeric_limits<streamsize>::max(), '\n'); is when it ignores up until '\n' or EOF \n is the delimiter meaning that, that is the character at which cin will stop ignoring.

Furthermore, numeric_limits<streamsize>::max() is basically saying there is no limit to the number of characters to ignore.

You need to use the header file #include<limits> to use this.

like image 125
Geno C Avatar answered Apr 22 '26 20:04

Geno C


I recommend separating the reading of input data from converting it to a number. A good method for this is to use stringstream. Here's a working example:

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

using namespace std;

int main()
{
    int num1;
    string input;
    bool cond{ false };
    cout << "enter 2:";
    while (!cond) {
        getline(cin, input);
        stringstream ss(input);
        ss >> num1;
        if( ss.fail() ){
            cout << "not a digit:";
            continue;
        }
        //
        if (num1 == 2)
            cond = true;
        else
            cout << "enter 2:";
    }

    return 0;
}
like image 23
sfb103 Avatar answered Apr 22 '26 19:04

sfb103