Search code examples
c++floating-pointinteger

If I input a float number when input is expecting an integer number, it updates the next float number value. Why does that happen?


I am a complete newbie to C++ programming. So, I was just trying out some basic C++ coding and I wrote the below program:

#include <iostream>

using namespace std;

int main()
{
    int number1;
    float number2;

    cout << "Enter number1 (integer)\r\n";
    cin >> number1;
    cout << "Enter number2 (float)\r\n";
    cin >> number2;

    cout << "Number1 is "<<number1<<"Number2 is "<<number2<<endl;
    return 0;
}

When I execute the above code and give say a number like "20.7" incorrectly instead of the integer that it expects when it prompts for number1,

the second cin statement gets skipped and number 1 is printed as 20 and number2 is printed as 0.7.

Why is that ? My expectation was the first cin should just make 20.7 as 20 and store it in number1 and second cin should not be skipped and prompt me for input.

Is that wrong expectation ? And why does this happen ?


Solution

  • You are passing float to an int. cin stops reading as soon as it sees '.' and the remaining number 7 is automatically taken as the input to the next cin.

    You may want to flush the input buffers after each read if you think that the values may not match the expected type.

    std::cin.clear(); and std::cin.ignore(100,'\n').

    which would be

    std::cin.clear();
    std::cin.ignore(whatever_num,'\n');
    

    More info can be found here and here

    Edit, for Pete's sake :

    1. >> Stream operator is the culprit.
    2. All input is TEXT.
    3. In the best case, read the input as TEXT and then parse/do whatever you want with it.
    4. Avoid cin.clear() and cin.ignore().