How can I tell if a string is made of all digits?

Let’s assume we want to write a function like the one below. Note that we use string s as a shortcut for the char *s (which we may or may not have discussed in your section yet)

bool all_digits(char *s);

The best way to accomplish something like this is to think through the nature of the problem a little bit. We can state the problem as follows:

  1. If every char in a string is a digit, then all_digits should return true
  2. If ANY char in a string is NOT a digit, then all_digits should return false

It’s the second statement that gives us the most direct way to solve this.

Inspect each char in the string ( s[i] , for example ). If any one of them is not a digit, return false. If the loop completes, then we must have the first case, so return true.

If that doesn’t help, you can review one solution below. Be sure you work out for yourself how it works.

One possible solution