How to read the nth number from a string of numbers?

How do i read the nth number in a string of n numbers separated by whitespace like the following.

112857 2498 4417878 1854672 417483 472422 37028136 7924624 0 2444476 9779560

The following numbers are from the /sys/block/sda/stat file on my Linux system.
I was thinking off using a stringstream object and writing the numbers into an integer a number of times before getting to the right count, but i'm not sure if this is the best way.

Thanks in advance.
Last edited on
An other option is to use a regular expression to capture the nth number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
long long nth_number( std::string text, std::size_t n ) // for first number, n == 1
{
    // (?:\d+\s+){4}
    //            \d+ one or more digits followed by
    //            \s+ one ore more white space characters
    // (?:)   do not capture
    // {4}    repeated exactly four times
    //
    // (\d+)  one or more digits, capture (numbered capture group 1)
    //
    // .*     zero or more characters
    const std::regex pattern( "(?:\\d+\\s+){" + std::to_string(n-1) + "}(\\d+).*" ) ;
    std::smatch results ;
    if( std::regex_match( text, results, pattern ) ) return std::stoll( results[1] ) ;
    else throw std::invalid_argument( "no match for nth number" ) ;
}

http://coliru.stacked-crooked.com/a/80f0710b296e883e
Cool! I new regex was the answer, I'm just not familiar with ECMAScript syntax. Thanks a bunch!
Modified ECMAScript is the default (the one used if no syntax option is specified).
The standard regular expressions library also supports basic/extended posix, awk, grep and egrep syntax options.
http://en.cppreference.com/w/cpp/regex/syntax_option_type
Topic archived. No new replies allowed.