-2

I have a vector of strings.

Vector <string> myVector;

And supposed currently myVector has 2 strings.

myVector[0] is "id1|Name1|Age1"
myVector[1] is "id2|Name2|Age2"

Now I want to split each string in the vector based on the delimiter "|" and store the result in a structure of id,name and age.

Can any body help?

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 1
    Take a look at the related questions on the right. If you have the pieces of the string, regular assignment to the struct members should be straightforward. – chris Sep 27 '17 at 12:52
  • 2
    Possible duplicate of [Most elegant way to split a string?](https://stackoverflow.com/questions/236129/most-elegant-way-to-split-a-string) – valleymanbs Sep 27 '17 at 13:00

2 Answers2

0

Something like that, you need to check it

struct{
   unsigned int id;
   std::string name;
   unsigned int age;
}MyStruct;

int main()
{
  std::string line;
  std::vector<std::string> myVector = {"id1|Name1|Age1","id2|Name2|Age2"};
  std::vector<MyStruct> myStruct;
  for (string::const_iterator it = myVector .begin(); it != myVector.end(); it++) 
  {
    vector<std::string> splitLine; 
    while(std::getline(*it,line,'|'))
       splitLine.push_back(line); 

    if (splitLine.size()> 0)
    {
       MyStruct mSt;
       mSt.id = (int)splitLine[0];
       mSt.name = splitLine[1];
       mSt.age= (int)splitLine[2];
       myStruct.push_back(mSt);
    }
  }


   return 0;
}
Ivan Sheihets
  • 802
  • 8
  • 17
0

This is simple with substr() and find().

#include <iostream>
#include <vector>
#include <string>

using namespace std;

struct Person
{
    string m_id;
    string m_name;
    int    m_age;
};

int main()
{
    vector<string> data;
    vector<Person> people;

    data.push_back("id1|Name1|25");
    data.push_back("id2|Name2|35");

    for(int i(0); i < data.size(); ++i){
        size_t idx  = data[i].find("|");
        string id   = data[i].substr( 0, idx);
        string name = data[i].substr(idx+1, data[i].find_first_of("|", idx) + idx - 1);
        string age  = data[i].substr( data[i].find_last_of("|") + 1 );

        Person p = {id, name, stoi(age)};
        people.push_back(p);

    }

    for(int i(0); i < people.size(); ++i)
        cout << people[i].m_id << "  " << people[i].m_name << "  " << people[i].m_age << endl;

    return 0;
}

and the output is

id1  Name1  25
id2  Name2  35
CroCo
  • 5,531
  • 9
  • 56
  • 88