OneBite.Dev - Coding blog in a bite size

check if a string contains only numbers in C

Code snippet on how to check if a string contains only numbers in C

  bool is_numeric(const char *str) 
  { 
  	int len = strlen(str); 

  	for (int i = 0; i < len; i++) 
  		if (str[i] < '0' || str[i] > '9') 
  			return false; 

  	return true; 
  } 

This code checks if a given string contains only numbers or not. It does this by iterating through the characters in the string one by one and comparing it to the ASCII values for the numbers ‘0’ and ‘9’. If any character in the string has a value outside of this range, then the function returns false, indicating that the string is not numerical. If all the characters in the string have a value between ‘0’ and ‘9’, then the function returns true. This means that the string is numerical and contains only numbers.

c