Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In order to detect that a string is a number it is usually propossed this:

bool isParam(string line)
{
    char* p;
    strtol(line.c_str(), &p, 10);
    return *p == 0;
}


Unfortunately for me *p points to first character if no number is inside, that is no 0

How I have to use the strtol()?

What I have tried:

Then I tried this that seems to work unless somebody writes decimals beginning by a point:

bool isNumber(string str1) 
{ 	
    char p = str1.c_str()[0]; return (p >= '0' && p <= '9'); 
}


After Richard MacCutchan post this worked for me:
bool isnumber(string str1) { return (isdigit(str1.c_str()[0])>0);}
Posted
Updated 4-Jul-17 23:11pm
v3
Comments
[no name] 4-Jul-17 6:41am    
And you tested also the case where one starts a number with "." or "+" or "-"?
:-)

Study the C library functions, and you will find isdigit().
 
Share this answer
 
If you need to detect also floating point values, then use strtod[^] (and afterwards check the value of the str_end parameter).
 
Share this answer
 
Because an unknown reason, I had an Assertion error when using isdigit() on character -96 ' ', so I should recommend using:
if (line[0] >= '0' && line[0] <= '9')

instead of isdigit()

Here is the function used (the line[] has tabulators):
//char line[]="N 2	32.1dC	28.7dC	25.2dC	20.7dC	19.6dC	18.5dC	74 %	67 %	52 %	4 kph	2 kph	0 kph";
double string_to_double2(char *line, int num)
{
	int i1 = 0, max = (int) strlen(line);
	for (int i = 0; i < max; i++)
	{
		//if (isdigit(line[0])>0)
		if (line[0] >= '0' && line[0] <= '9')
		{
			if (i1 == num) return strtod(line,&line);
			strtod(line, &line);i1++;
		}
		else line++;
	}
	return -99999999;
}
 
Share this answer
 
v2
Comments
Richard MacCutchan 5-Jul-17 5:31am    
I suggested isdigit just as a starting point to get you thinking. As a developer you need to consider all the possible situations that may occur in your data, and code for each of them.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900