c++iostreamcinistream

std::cin , unwanted behaviour. and how can I fix this?


I tried to play with some code to test overloading functions. The overloading part went well, however, I learned something about std::cin that made me feel stupid for not noticing it before!

#include <iostream>
void read (int *var){
    std::cout<<std::endl<<" input :";
    std::cin>>*var;
}
void read (float *var){
    std::cout<<std::endl<<" input :";
    std::cin>>*var;
}
void read (char *var){
    std::cout<<std::endl<<" input :";
    std::cin>>*var;
}
void read (bool *var){
    std::cout<<std::endl<<" input :";
    std::cin>>*var;
}
int main(){
    int a;
    float x;
    char c;
    bool s;
//  std::cin>>a;
//  std::cin>>x;
//  std::cin>>c;
//  std::cin>>s;
    read (&a);
    read (&x);
    read (&c);
    read (&s);
    std::cout<<a<<std::endl<<x<<std::endl<<c<<std::endl<<s<<std::endl;
    return (0);
}

When compiled with g++ this is what happens:

$ g++ test1.cpp -o test
$ ./test

 input :1.2

 input :
 input :a

 input :0
1
0.2
a
0

I already tried many values and added some instructions in between, but I still get the same behaviour, which is annoying if I try to read multiple values and more so if they were in different types.

The commented text does basically the same as the 'read' functions below and has the same behaviour. I am using a function because I just wanted to do so :D


Solution

  • This is not a strange behaviour what really happens is when this line is executed in the read int function:

     std::cin>>*var;
    

    it expects an integer from your keyboard buffer and when you enter this as input:

    1.2
    

    the cin object reads the first digit until the decimal point because it is the integer part and leave the remaining characters inside the buffer so variable a will have the value 1 and the characters .2 will be lifted over in the buffer.

    So when the read float function executes it doesn't wait for your input because there is already a floating point number inside the buffer so it reads it and stores it in the variable so it's value becomes 0.2.