isdigit ??

How can I check if a string contains numbers?
I tried isdigit, but it isn't working.
isdigit(c) returns true if the character c is a number 0-9. Since you're using a string, an array of characters, you need to loop through the entire string with a for loop, and then check each character to see if it is a digit. A sample would be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <cctype>

int main() {
   std::string myString = "My age is 15";

   for (int i = 0; i < myString.length(); i ++)
      if (isdigit(myString[i])
         std::cout << "A number was found at index " << i
                   << ": " << myString[i] << "\n";

   return 0;
}
A number was found at index 10: 1
A number was found at index 11: 5
Last edited on
Gotcha. Ok. With the for loop it actually works...i appreciate it.

Thanks!
Topic archived. No new replies allowed.