C++ statement that prints yes if digit in string

Oct 29, 2012 at 6:44pm
Write a c++ statement that print's "yes" if there is a digit in the variable sport3. I'm trying to find the correct string command to do this an easy way.
Oct 29, 2012 at 7:07pm
The "correct command" is the standard algorithm std::any_of.:)
Last edited on Oct 29, 2012 at 7:07pm
Oct 29, 2012 at 7:13pm
I was looking through the string references to try to find one of those. I found isgidit() but don't think that will work in this case. That's why I was wondering if there was something like isdigit() in the string reference that would let me be able to to that.
Oct 29, 2012 at 7:38pm
Vlad's way is fine.

If you're wanting to use isdigit() then that's fine too. You'd just have to loop through each character of the string and pass each character into isdigit().

You could use some sort of boolean flag to highlight whether or not you've found a digit.
Oct 29, 2012 at 7:49pm
So something like:

1
2
3
4
5
6
string sport3 = "Baseball2day";
bool digit = false;
    while(digit)
        {
            isdigit(sport3);
        }


Of course that wouldn't work so how would I go about stepping through each char?
Oct 29, 2012 at 7:54pm
1
2
3
4
5
for ( int i = 0; i < sport3.length(); i++ ) {
    if ( isdigit( sport3[ i ] ) {
        return digitDetected;
    }
}


Something like this
Last edited on Oct 29, 2012 at 7:54pm
Oct 29, 2012 at 8:12pm
Would you still do the sport3[ i ] since its not an array but just a string?
Oct 29, 2012 at 8:17pm
Look up the string object. The [] operator exists for it so that it works like an array.
Oct 29, 2012 at 8:27pm
Well you were right about the [] so there's something new you learn. Got it working going off of Fransje's code so thanks for that. Instead of bool I just had it cout if there was a digit. Thanks for the help.
Topic archived. No new replies allowed.