Hi.

I've searched the daniweb question database, and was not satisfied with solutions I found there.

I have a string that looks like this...

"100 1.745329252 0.984807753 -0.173648178 -5.67128182"

not exactly words, but I want to select say, the third "word" of this string (0.984807753) into a variable. The whitespaces make it a little more taxing. How should I go about doing this?

Thanx in advance.

Depends on a number of things.

-Are you using std::strings or char arrays[]
-Do you want to convert the string to a double?
-Are the variables separated by a single whitespace or multiple whitespaces or perhaps even tabs?
-Do you want to store the numbers in an array of doubles, or a vectors of doubles or neither...
-Will there always be the same number of variables per line? If so did you want to store the variables statically rather than in an array.

i.e
double a = 0.1
double b = 0.3423

etc.

Depends on a number of things.

-Are you using std::strings or char arrays[]
-Do you want to convert the string to a double?
-Are the variables separated by a single whitespace or multiple whitespaces or perhaps even tabs?
-Do you want to store the numbers in an array of doubles, or a vectors of doubles or neither...

its a std::string
Yes. I the variable I will use for storage will be a double.
They might be tabs. The numbers are basically copied and pasted from an excel file into notepad.
I dont need to store all of the numbers. Just one.

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

class Foo
{
public:
  double bar ( string line )
  { 
    stringstream ss ( line ); 
   //robust enough to parse by whitespaces and tabs

    string word;

    int counter = 0;
    while ( ss >> word )
    {
      if ( counter == 2 )
      { 
        double x;
        //convert to double
        istringstream ins;
        ins.str ( word );
        ins >> x;

        return x;
      }
      counter++;
    }
  }
};

int main()
{
  Foo shit;
  cout << shit.bar ( "100 1.745329252 0.984807753 -0.173648178 -5.67128182" );
  cin.get();
}

How about to get you started.

Comments
There's nothing more to add really.
This article has been dead for over six months. Start a new discussion instead.