Parse the string to get the nth field

Im trying to parse the line located in / proc / stat on a Linux file system using C ++

I raised and saved the string as a variable in a C ++ program

I want to raise individual values ​​from a string. Each value is separated by a space.

I want to know how, for example, to raise the 15th value from a string.

+3
source share
7 answers

std::stringseparated by spaces can be automatically analyzed from any ostream. Just put the whole line in std::istringstreamand parse the nth line.

std::string tokens;
std::istringstream ss(tokens);

std::string nth;
for (int i = 0; i < 15; ++i)
  ss >> nth;

return nth;
+4
source
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

// return n'th field or empty string
string Get( const std::string & s, unsigned int n ) {
    istringstream is( s );
    string field;
    do {
        if ( ! ( is >> field ) ) {
            return "";
        }
    } while( n-- != 0 );
    return field;
}

int main() {
    string s = "one two three four";
    cout << Get( s, 2 )  << endl;
}
+3
source
+1

I would use the Boosts String algorithm separation algorithm:

#include <string>
#include <vector>

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

std::string line = "...."; // parsed line
std::vector<std::string> splits;
boost::algorithm::split( splits, parsed_line, boost::is_any_of( " " ) );

std::string value;
if ( splits.size() >= 15 ) {
  value = splits.at( 14 );
}
+1
source

You can use boost::tokenizerwith space as a separator and iterate over values.

0
source

you can use the function strtokwith some counter to stop when you reach the nth value

0
source

You can use it std::string::findto search for a space and repeat until the 15th value is found.

0
source

Source: https://habr.com/ru/post/1735450/


All Articles