3

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.

ST3
  • 8,826
  • 3
  • 68
  • 92
paultop6
  • 3,691
  • 4
  • 29
  • 37
  • 2
    Did you notice that you can *accept* answers to your previous questions by using the checkmark? That marks the question as closed and provides feedback to those who answered. – Georg Fritzsche Mar 04 '10 at 17:32

7 Answers7

4

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
  • 53,344
  • 14
  • 119
  • 168
  • thanks, worked a treat, although im having problems trying to read the contents of /proc/stat, but thats another question, lol! – paultop6 Mar 04 '10 at 19:23
3
#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;
}
2

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 );
}
Mathias Soeken
  • 1,293
  • 2
  • 8
  • 22
0

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

Timo Geusch
  • 24,095
  • 5
  • 52
  • 70
0

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

Community
  • 1
  • 1
Milliams
  • 1,474
  • 3
  • 21
  • 30
  • 2
    Linking to other questions/answers is usually done via comments not answers, especially if you don't add any information yourself. – Georg Fritzsche Mar 04 '10 at 17:29
0

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

grapkulec
  • 1,022
  • 13
  • 28
0

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

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154