将字符串解析为结构变量 [英] Parsing String into struct variables

查看:56
本文介绍了将字符串解析为结构变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个字符串解析为一个包含不同变量的结构向量.这是我到目前为止所拥有的,但似乎不起作用.

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

}

推荐答案

尝试使用 istringstream 对象:

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

这篇关于将字符串解析为结构变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆