How to filter out integers in a string of Vectors

I am new to C++ and the code below is a general concept of what I have

1
2
3
4
5
std::vector<string> x;
std::cout << "Please enter in values ";
std::string numbers;
std::getline(std::cin, numbers);
x.push_back(numbers)


Let's say the user inputted
1
2
 
3.9823 m/s 34.0 km/s 222 m/s


I was wondering how am I able to only grab the numbers in the string and disregard the units?

I want the values 3.9823, 34.0, and 222

Thank you!
Last edited on
Will there always be units? Will the units ever contain spaces?

Also, line 4 of your example, you switched around x and numbers.
Yes, there will always be units and no they will not contain spaces.

And thanks! Edited.
You could use a string stream and stream the numbers and discard or stream the units somewhere else.

http://www.cplusplus.com/reference/sstream/stringstream/?kw=stringstream

ex:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
 
 
int main()
{
	std::string numbers( "3.9823 m//s 34.0 km//s 222 m//s" );
	std::stringstream ss( numbers );
	std::vector<double> vec;
	double x;
	std::string delim;
	while( ss >> x >> delim )
		vec.push_back( x );
 
	for( const auto &it : vec )
		std::cout << it << ' ';
	return 0;
}



Just make sure you format it in the same way.

The example is formatted in form of: [double][unit] -> separated with spaces
[edit] fixed spelling error[/edit]
Last edited on
Topic archived. No new replies allowed.