Comma in a cin command


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
using namespace std;
int main()
{
	int a,b;
	cout<<"Key in the value of a";
	cin>>a;
	cout<<"Key in the value of b";
	cin>>b;

	cout<<"the sum of a and b is"<<a+b;
	cout<<"the diffrence of a and b is"<<a-b;

	return 0;
}

i am new to C++, when i try to key in integer a as 13,708(with comma),the program do not allow me to enter value of b anymore
and its auto pop out some result,why it can happen,sorry for my bad english


the sum of a and b is-858993447
the diffrence of a and b is858993473

it come out this kind of result why???
Because cin doesn't realize that the comma is part of the number and so it stores "13" to a and then tries to shove a comma into b (which obviously fails).

The garbage values you're getting as output are probably because b is uninitialized, so you're basically outputting 13+garbage value and 13-garbage value.

It should work if you enter it as "13708" (no comma).
Last edited on
So the program just simple take any value and assign for variable b,and it execute the calculation and get garbage answer??
So initially, a and b are uninitialized (so they can contain just about anything).
The program asks you to input a value for a.
You enter "13,708".
The program starts reading off the number, but then stops at the comma because that's not a number.
It still managed to pull a "13" off of the input stream, so that's the value it puts into a.

The program then tries to input a value for b.
Normally, it would stop and wait for you to enter something, but since there's already some input that's still waiting in the input buffer (namely, the ",708" part), it figures that it already has input so it doesn't need to wait for you to enter more.
This time, it chokes up on the comma (because that's not a number), so the input silently fails and nothing happens to b (which is still uninitialized and so still contains a garbage value).

Then your program spits out the result of the calculations.
Last edited on
Topic archived. No new replies allowed.