Parsing String into struct variables

时光总嘲笑我的痴心妄想 提交于 2021-01-27 15:13:45

问题


Im trying to parse a string into a vector of a struct that has different variables in it. This is what I have so far but it doesnt seem to work.

struct client
{
    string PhoneNumber;
    string FirstName;
    string LastName;
    string Age;
};
int main()
{
    string data = getClientDatabase();

    vector <client> clients;

    parse_string(data, clients);
    return 0;
}

string getClientDatabase()
{
    return
        "(844)615-4504 Sofia Ross 57 \n"
        "(822)516-8895 Jenna Doh 30 \n"
        "(822)896-5453 Emily Saks 43 \n"

}

So this function I wrote doesnt seem to work, im sure there is an easier way but i cant figure it out.

void parse_string(string data, vector <client> &clients)
{
    string temp;
    string temp1;
    string temp2;
    string temp3;

    int i = 0;
    int j = 0;
    int k = 0;
    int l = 0;

    while (i < data.length())
    {
        if (data.at(i) != ' ')
        {
            temp.push_back(data.at(i));
            j++;
        }
        else
        {
            clients.at(i).PhoneNumber = temp;
        }

    }
    if (data.at(j) != ' ')
    {
        temp1.push_back(data.at(j));
        k++;
    }
    else
    {
        clients.at(i).FirstName = temp1;
    }

    if (data.at(k) != ' ')
    {
        temp2.push_back(data.at(k));
        l++;
    }
    else
    {
        clients.at(i).LastName = temp2;
    }

    if (data.at(l) != ' ')
    {
        temp3.push_back(data.at(l));

    }
    else
    {
        clients.at(i).Age = temp3;
    }
    i++;

}

回答1:


Try using an istringstream object:

void parse_string(string data, vector <client> & clients) {
  istringstream iss(data);
  for (size_t i=0; iss >> clients.at(i).PhoneNumber; ++i) {
    iss >> clients.at(i).FirstName
        >> clients.at(i).LastName
        >> clients.at(i).Age;
  }
}



回答2:


you can try this code:

 void parse_string(string data, vector <client> & clients)
 {
     struct client tempS;
     istringstream iss(data);
     for (size_t i=0; iss >> tempS.PhoneNumber; ++i)
     {
         iss >> tempS.FirstN >> tempS.LastN >> tempS.Age;
         clients.push_back(tempS);
     }
 }

//test code

vector <client>::iterator it = clients.begin();
     for(; it != clients.end(); ++it )
    {
        cout << it->PhoneNumber << " "
             << it->FirstN << " "
             << it->LastN << " "
             << it->Age << endl;
    }


来源:https://stackoverflow.com/questions/27098305/parsing-string-into-struct-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!