input a number with a comma in it

When I input a comma number, like 1,000 into this the console closes early. Anyone know why? The type is double. The same thing happens when the type is integer and I input a number with a decimal, like 11.5

#include <iostream>
using namespace std;

int main()
{
char ch;
double hours, rate, pay;

// Get the number of hours worked.
cout << "How many hours did you work? ";
cin >> hours;

// Get the hourly pay rate.
cout << "How much do you get paid per hour? " ;
cin >> rate;

/* had a little problem with mixing cin << and cin.get(). The
window closes never displaying the calculated earnings. I'm
repairing by using cin.ignore() by skipping next character */
cin.ignore();

// Calculate the pay.
pay = hours * rate;

// Display the pay.
cout << "You have earned $ " << pay << endl;
cin.get(ch);
return 0;
}
In C++, comma-separators for thousands are not part of a number, as decimal points aren't for integers, so as soon as the operation finds either the comma or the point, the extraction operation ends, leaving that character as the next to be extracted. Subsequent extraction operations find that character as the first one to be extracted, so they all return.

The extractor operator cin>> is a little pesky and difficult to manage if the user does not enter what you expect. An alternative approach, although more cumbersome, is to use getline + stringstreams, as described at the end of:

http://cplusplus.com/doc/tutorial/basic_io.html
Hey ddollar,

commas are used to seperate expressions.
just type 1000 instead of 1,000

I don't if this will help ya, but if you don't want the program to end as soon as you run it, try system("pause") . This way it will end whenever you want it to.

Or try Sleep(...) within the windows.h header file. every 1000 equals 1 second.

Sleep(3000) equals 3 seconds.

And By the way, try using 'long' instead of 'double' that way the numbers will be
displayed with dots without any weird signs
Last edited on
Topic archived. No new replies allowed.