C++/checking if a string consists of all numbers or not.
Hi, i was wondering if there was a way to check if a string consists of all numbers or not.
i know that it first transfers all numbers into it's char-code # and then goes through a for loop
and checks if the char-code # is the char# or 0~10.
Hello James, thank you for the question.
Though there is no function to call to directly determine if a string is all numbers or not, you could use the function atoi() to figure it out. atoi() takes a string and converts it to an integer. You could probably use a double for-loop to figure it out. Here is an example:
char str = "12345";
for(int i = 0; i < strlen(str) - 1; i++)
for(int j = 0; j <= 9; j++)
if(atoi(str[i]) == j)
// index is a number
So this goes index by index comparing each index to the numbers 0-9, which it would have to be if the string is all numbers. You could probably encapsulate that algorithm into a function if you wanted.
I hope this information was helpful.