Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing String into struct variables

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++;

}
like image 793
chillax786 Avatar asked Jul 15 '26 12:07

chillax786


1 Answers

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;
  }
}
like image 117
ooga Avatar answered Jul 18 '26 01:07

ooga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!