+ 2

Function Overloading

Hi, while learning the examples in the C++ course I tinker and experimenting on stuff. Take a look at the code: #include <iostream> using namespace std; void pnum(int a); void pnum(float a); int main() { int x; float y; cout << "Enter number: "; cin >> x; cout << endl; pnum(x); cout << "Enter number: "; cin >> y; cout << endl; pnum(y); return 0; } void pnum(int a) { cout << "number is " << a << endl; } void pnum(float a) { cout << "number is " << a << endl; } If I enter a float-type number FIRST, it prints the integer part and then automatically prints the remaining fracture part. How and Why? Thanks

30th Jun 2017, 9:45 PM
Roman
Roman - avatar
6 Answers
+ 5
It is because you are using cin. When you take the integer part out of the input stream and store it into the int number, there is still the remaining decimal part still left in the stream, which it automatically stores into the float number, ignoring any further input.
1st Jul 2017, 12:15 AM
Zeke Williams
Zeke Williams - avatar
+ 3
That is strange, maybe try this code in a different compiler? It could be result of how Code Playground deals with the input, where it places the extra decimals lost from the down-cast into the other variable as if that was the input.
30th Jun 2017, 5:20 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
@Zeke Never knew cin did that, thanks for the info!!!
1st Jul 2017, 1:46 AM
Rrestoring faith
Rrestoring faith - avatar
+ 2
I am using Codeblocks with GNU compiler on Win 10. Running it in Visual 2015 gives the same result. for example: Enter number: 5.5 number is 5 Enter number: number is 0.5 It's really interesting to know what's happening here. I know assembly so it would be even a greater pleasure to understand it to the physical level of the cpu.
30th Jun 2017, 6:05 PM
Roman
Roman - avatar
+ 2
You can use the member function peek(): cin >> x; // you enter 4.34 char c = cin.peek(); // c is equal to '.' http://www.cplusplus.com/reference/istream/istream/peek/
1st Jul 2017, 4:26 PM
Zeke Williams
Zeke Williams - avatar
0
Oh right, I didn't notice that I pass an int parameter. So how do I check the stream buffer for the remaining decimal number? I can't find a good example on google.
1st Jul 2017, 10:24 AM
Roman
Roman - avatar