Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is a number?

Tags:

I want to check if a string is a number with this code. I must check that all the chars in the string are integer, but the while returns always isDigit = 1. I don't know why that if doesn't work.

char tmp[16]; scanf("%s", tmp);  int isDigit = 0; int j=0; while(j<strlen(tmp) && isDigit == 0){   if(tmp[j] > 57 && tmp[j] < 48)     isDigit = 0;   else     isDigit = 1;   j++; } 
like image 989
Astinog Avatar asked May 20 '13 07:05

Astinog


People also ask

How do you check if a string is an integer or int?

The most efficient way to check if a string is an integer in Python is to use the str. isdigit() method, as it takes the least time to execute. The str. isdigit() method returns True if the string represents an integer, otherwise False .

How do you check if a string is a number in C++?

Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.

How do you test if a string is a number Python?

Python String isnumeric() MethodThe isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .

How do you check if there is a number in a string Java?

Use the isDigit() Method to Check if String Contains Numbers in Java. To find an integer from a string, we can use this in-built function called isDigit() .


1 Answers

Forget about ASCII code checks, use isdigit or isnumber (see man isnumber). The first function checks whether the character is 0–9, the second one also accepts various other number characters depending on the current locale.

There may even be better functions to do the check – the important lesson is that this is a bit more complex than it looks, because the precise definition of a “number string” depends on the particular locale and the string encoding.

like image 193
zoul Avatar answered Nov 16 '22 18:11

zoul