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:
- If every
char
in astring
is a digit, thenall_digits
should returntrue
- If ANY
char
in astring
is NOT a digit, thenall_digits
should returnfalse
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.