chadpeppers
chadpeppers

Reputation: 2057

C++ String to String Array by Delimeter

I have a file that is outputting information into a class. Specifically one of the strings I am trying to output will go into a vector. The problem is that I am trying to take a string (in this case of interests) which would be formatted:

interest_string = "food, exercise, stuff"

So basically I want to turn the string above into a string of arrays or somehow copy the above string to a vector in each individual string separated by the comma delimeter.

void Client::readClients() {
    string line;


    while (getline( this->clients, line ))
    {

        string interest_num_string, interest_string;

        istringstream clients( line );
        getline( clients, this->sex, ' ' );
        getline( clients, this->name, ',' );
        getline( clients, this->phone, ' ' );
        getline( clients, interest_num_string, ' ' );
        getline( clients, interest_string, '.' );

        this->interests = atoi(interest_num_string.c_str());

        cout << this->sex << "\n" << this->name << "\n" << this->phone << "\n" << interest_num_string << "\n" << interest_string;
    }

    this->clients.close();
}

Upvotes: 0

Views: 152

Answers (3)

saha
saha

Reputation: 97

Simple c++ piece of code :

  string s = "abc,def,ghi";
  stringstream ss(s);
  string a,b,c;
  ss >> a ; ss.ignore() ; ss >> b ; ss.ignore() ; ss >> c;    
  cout << a << " " << b << " " << c << endl;

Output :

abc def ghi

Upvotes: 0

Captain Obvlious
Captain Obvlious

Reputation: 20063

You could use a vector or other suitable container. You will need to create a "person" class that will contain all of the data you read in and place into the container.

void Client::readClients(std::vector<MyClass*>& myPeople)
{
    //  ... other parts of your code

    // Create a person
    pointerToPerson = new Person();

    // read them in
    getline(clients, pointerToPerson->field, ' ');

    // After you load a person just add them to the vector
    myPeople.push_back(pointerToPerson);

    // more of your code ...
}

Upvotes: 0

djechlin
djechlin

Reputation: 60758

Hint: an alternate signature for getline is

istream& getline ( istream& is, string& str, char delim );

strtok in C is also a viable option that isn't too brutal on low-level string manipulation.

Upvotes: 2

Related Questions