i don't understood why pos change.

1
2
3
4
5
6
7
8
9
10
11
12
13
size_t finddigit(string &str,size_t pos)
{
    if(pos>=str.size())return -1;
    while(!isdigit(str.substr(pos,1)[0])&&pos<str.size()-1){pos++;cout<<"pos="<<pos<<endl;}
    cout<<"lastpos="<<pos;
    if(!isdigit(str.substr(pos,1)[0]))return -1;
    else return pos;
}

in main

 string s1="012abc";
cout<<finddigit(s1,3)<<endl;


it gives ...
i don't understood
----------------
pos=4
pos=5
lastpos=54294967295

Process returned 0 (0x0) execution time : 0.000 s
Press any key to continue.

why is doing that?


You begin at the f4th Index of the string and you try to find a digit from there.

Since you chose to return a size_t value
which basicly is an "unsigned int"
your "-1" you return (because you don't find a digit after the 3rd index)
is interpreted as an unsinged int which is this big number

"-1" in binary is represeted as 32 x 1. (11111111111111111111111111111111...)
when you now interpred this as an "unsigned int" it's "4294967295" and not -1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>

std::size_t finddigit1( const std::string& str, std::size_t pos = 0 )
{
    if( pos >= str.size() ) return std::string::npos ;
    return str.find_first_of( "0123456789", pos ) ;
}

std::size_t finddigit2( const std::string& str, std::size_t pos = 0 )
{
    for( ; pos < str.size() ; ++pos )
        if( std::isdigit( str[pos] ) ) return pos ;

    return std::string::npos ;
}

std::size_t finddigit3( const std::string& str, std::size_t pos = 0 )
{
    if( pos >= str.size() ) return std::string::npos ;
    auto iter = std::find_if( str.begin()+pos, str.end(),
                                []( char c ) { return std::isdigit(c) ; } ) ;
    return iter != str.end() ? iter-str.begin() : std::string::npos ;
}

int main()
{
    const std::string str = "abcde 5 fghij 1 klmno 9 pqrst" ;
    std::cout << str << "\n012345678901234567890123456789\n"
               << finddigit1(str) << '\n' // 6
               << finddigit2( str, 8 ) << '\n' // 14
               << finddigit3( str, 17 ) << '\n' // 22
               << finddigit1( str, 25 ) << '\n' ; // std::string::npos
}
Dear JLBorges thank you.

Very good code indeed.

Jim
a problem ...

compiler says ...

error: 'find_if' is not a member of 'std'|
Make sure you including the <algorithm> header as the example was.
Topic archived. No new replies allowed.