Hi

I have a string & I want to grab certain elements out of the string & save them in an array. I have searched for an answer to this but I have not found a solution to what I am trying to do.

What I am trying to do:

Below is a string:

AWL,0.003,-0.001,0.003,0.004,0.004,0.004,0.003,989216,,17500,53,-18

I would like to grab the numbers in bold and store them each in separate array:

AWL,0.003,-0.001,0.003,0.004,0.004,0.004,0.003,989216,,17500,53,-18

I have found lots of ways to do this if I want all of the elements of the string but not how to do it when I only want certain parts.

Any advice? :)

>I have found lots of ways to do this if I want all of the elements of the string but not how to do it when I only want certain parts.
What's a funny statement... If you can get all elements (by the way, where is your code?;)), it's so easy to get selected ones...

There are lots of methods to do that.

For example:

#include <string>
#include <vector>
#include <sstream>

using namespace std;

void Tokenize(const string& s, vector<string>& vtok, char delim = ',')
{
    istringstream is(s);
    string t;
    vtok.clear();
    while (getline(is,t,delim))
        vtok.push_back(t);
}

template<typename T>
inline
bool getVal(T& val,const std::string& s)
{
    std::istringstream is(s);
    return (is >> val) != 0;
}

int main()
{
    string s("AWL,0.003,-0.001,0.003,0.004,0.004," // 0..5
             "0.004,0.003,989216,,17500,53,-18");  // 6..12
    vector<string> v;

    Tokenize(s,v,',');
    double  x;  // 4-th field
    int     n;  // 10-th field

    if (10 < v.size() && getVal(x,v[4]) && getVal(n,v[10]))
        cout << x << ' ' << n << endl;
    return 0;
}

u can find starting index of the part that you want. then u an search and place the items in the arrays.

u can run a for or while loop to search for the elements. also u can access a string like an array and when u get the starting index u can use the for or while loop to search the rest of the string and then as u go along u can save the part of the string in an array.

its quite an easy program to make.

also then you can run an outer loop which will allow u to check for other words as well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.