Limit the input stream to values of type int

3
#include <iostream> 
#include <limits> 

using std::cout;
using std::cin;
using std::endl;
int getVar(int num);
int getInt(int num);

int main(){

    int n;
    cout<<"Insira um inteiro. \n\n";
    getInt(n);


    return 0 ;
}
int getInt(int n){

    cin>>n;
    return getVar(n);
}

int getVar(int num){

    if(!(cin>> num &&  !num % 2 == 0)){

        cout<< num <<" Entrada nao corresponde ao tipo de variavel solicitado.\n\n";
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        getInt(num);
    }
    else{
        cin.clear();
        cout<<"\n"<< num <<" Entrada recebida com sucesso!!! \n";
        return num;
    }
}

When I type a number that is accepted by the function, in the case of an integer, I have to type it twice in order for it to be fetched, I would like it to capture the direct input on the first attempt.

    
asked by anonymous 09.01.2016 / 21:03

1 answer

3

First, if you are going to get a number that can be written with floating point, the type of the variable must be float and not int . It's weird to do this, because if you want whole numbers, ask for integers, then you do not have to do anything. But it must be some crazy exercise meaningless. It may use another form, but it is more complex.

To know if a number that can have decimal part is just integer, simply compare it with its integer part, doing a simple cast as done in the condition. So it is comparing the number with decimal and the number converted to integer. If they are the same it is because the conversion did not lose anything, so it was already integer.

I took all the unnecessary statements and functions that were not bringing anything useful to the code, on the contrary, it was causing problems.

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

int main() {
    float n;
    cout << "Insira um inteiro." << endl;
    while (true) {
        cin >> n;
        if (!cin.fail() && n == (int)n) {
            break;
        }
        cout << n << " - Entrada nao corresponde ao tipo de variavel solicitado." << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }   
    cout << endl << n << " - Entrada recebida com sucesso!!!" << endl;
    return 0;
}

See running on ideone .

The check if cin.fail() was used to prevent typing non-numeric characters.

You can simplify the code a little more if you accept a small change in behavior. Could not give the error message, would have to just ask the number again.

    
09.01.2016 / 23:15