Reading numbers from the same line

Guys! Having trouble here. suppose a user enters in these numbers with spaces or maybe even commas. What function do I use to get all of the numbers from the same line even characters. Would really appreaciate it if someone helps me this.



double number3;
cout<<"\n\n\n\tEnter in number 3: ";



cin>>number3; //suppose I typed in 123 32,345. How can i get all these numbers under one line. For instance, convert 123 32,345 in to 123323454?
cout<< "\n\nNumber 3 is " << number3;
}
I suppose one solution would be to store it as a string, delete whitespace and punctuation and then convert that string to an int.
Appreciate your response! I'm sorry, I was not unable to understand that. I thought string can be used for characters only, instead of numbers. Moreover, how would I enter it in my code if I wanted to delete it. I was thinking ignore...but then when I test it or debug it. I get an empty value for number3.
Numbers can be considered characters too, you might want to take a look at:

http://www.cplusplus.com/reference/string/string/erase/

and at:

http://www.cplusplus.com/reference/cctype/
Example using stringstream. http://www.cplusplus.com/reference/sstream/stringstream/

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
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
	string origin;
	const string NUMS = "1234567890";
	stringstream number;
	int num;

        //get the number
	cout << "Enter number:  ";
	getline(cin, origin);

        //get all numbers out of original
	while(origin.length() > 0)
	{
                //if this character is a number
		if((int)NUMS.find(origin.substr(0, 1)) >=0)
                        //add character to stringstream object number
			number << origin.substr(0, 1);

                //remove first character
		origin = origin.substr(1);
	}

        //convert number to an int
	number >> num;

	cout << num << endl;
}
Last edited on
Topic archived. No new replies allowed.