Distinguishing between numbers and other symbols

Hi everyone,

I'm reading a text file and extracting pieces of information of it by means of parsing (line by line).
Here is an example of the text file:

1
2
3
 0    1.1       9     -4
 a    #!b     .c.     f/ 
a4   5.2s   sa4.4   -2lp


So far, I'm able to split each line using empty spaces ' ' as separators. So I can save, for example, the value of "1.1" into a string variable.

What I want to do (and here is were I'm stuck) is to determine if the piece of information that I'm reading represents a number. Unsing the previous example, these strings do not represent numbers: a #!b .c. f/ a4 5.2s sa4.4 -2lp
Alternatively, these strings do represent numbers: 0 1.1 9 -4

Then I would like store the strings that do represent numbers into a double type variable.

So, How can I distinguishing between numbers and other symbols?

Thanks.
Last edited on
Try to read, if it fails then it was not a number.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <sstream>

int main(){
	std::string word;
	while(std::cin >> word){ //separate by white-space
		std::istringstream input(word);
		double d;
		if(
			not (input>>d) //trying to read as a double
			or  input.rdbuf()->in_avail() not_eq 0 //handle cases like -2lp (starts with a number)
		)
			std::cout << "not a double\n";
		else
			std::cout << "a double " << d << '\n';
	}
}
Topic archived. No new replies allowed.