stringstream problems

Hi guys,

Need a little help with string stream. This is my first time using it, but with little success. I need to take a double number, make it a string, then format it. Put in commas, a dollar sign etc.

However, the stringstream object is either dropping decimals, not recognizing them whatsoever, or putting my number into scientific notation. I am looking to do this in a class context without pointers or anything advanced (if it can be helped)

Thanks,

Mike

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

const int MAX=1000;
class Money
{
public:
	Money();
	void convert(const double n);
	void print() const;

private:
	string temp, final;
	

};

int main()
{	
	char choice;
	double number=123462.12;
	Money money;
	cout.setf(ios::fixed);
	cout.setf(ios::showpoint);
	cout.precision(2);

	do
	{
		cout<<"Enter a number: ";
		//cin>>number;
		while(number<0)
		{
			cout<<"Can't be less than zero, enter again: ";
			cin>>number;
		}
		money.convert(number);
		

		cout<<"again(y/n): ";
		cin>>choice;
	}while(choice=='y');
	exit(1);
	_getch();
}
Money::Money(){}
void Money::print() const
{
	cout<<final<<endl;
}
void Money::convert(const double n)
{

	

	stringstream ss;
	ss<<n;
	ss>>temp;//puts double into string object
	cout<<temp;


}
I believe stringstream can be used exactly like cin and cout.

That means you can do:
1
2
ss.precision(5);//sets number of decimal points
ss<<fixed;// you can also do this to get numbers like 1.50 instead of 1.5 

Bingo!!

Thanks a lot!
Topic archived. No new replies allowed.