gpt4 book ai didi

c++ - 将字符串解析为结构变量

转载 作者:太空狗 更新时间:2023-10-29 23:02:54 25 4
gpt4 key购买 nike

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

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"

}

所以我写的这个函数似乎不起作用,我确定有更简单的方法,但我想不通。

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

关于c++ - 将字符串解析为结构变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27098305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com