tags:

views:

127

answers:

7

Hi Guys

Im trying to parse the string located in /proc/stat in a linux filesystem using c++

I have lifted and saved the string as a variable in a c++ program

I want to lift individual values from the string. Each value is separated by a space.

I want to know how i would, for example, lift the 15th value from the string.

Regards

Paul

A: 

You could use boost::tokenizer with space as a separator and iterate over the values.

Timo Geusch
+1  A: 

See this SO and that should answer most of your question.

Milliams
Linking to other questions/answers is usually done via comments not answers, especially if you don't add any information yourself.
Georg Fritzsche
A: 

you could use strtok function with some counter to stop when you reach nth value

grapkulec
A: 

You could use std::string::find to find a space and repeat until the 15th value is found.

Thomas Matthews
+2  A: 

std::strings separated by spaces can be automatically parsed from any ostream. Simply throw the entire line into an std::istringstream and parse out the nth string.

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

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

return nth;
Peter Alexander
thanks, worked a treat, although im having problems trying to read the contents of /proc/stat, but thats another question, lol!
paultop6
+3  A: 
#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;
}
anon
+1  A: 

I would use the split algorithm from the Boosts String Algorithms here:

#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 );
}
Rupert Jones