这段程序为什么是这样的结果,有没有人帮i我看看
#include <iostream>
#include <string>
using std::string;
struct ROLE //定义角色,角色属性有id和exp两种
{
string id;
int exp;
};
int getDatalength(string strData) //获取字符串角色数量,以分号为标志,一个角色有id和exp两个属性,两个分号代表一个角色
{
int count = 0;
for (int i = 0; i < strData.length(); i++)
{
if (strData[i] == ';')
{
count++;
i += 3; //分号后面三位肯定不是分号,分号后面三位要么是"id"要么是"exp"
}
}
count /= 2;
return count;
}
string getneedstr(string substrIn,string strData,int s_begin,int s_end) //获取对应的id或exp的值
{
int num = substrIn.length()+1; // 获取id=或exp=的长度
s_begin = strData.find("substrIn", s_begin); //从零开始,获取第一个id或exp 的位置
s_end = strData.find(";", s_begin+3); //从id开始,获取第一个分号的位置
string strOut = strData.substr(s_begin + num, s_end - s_begin - num); //截取从id开始,到分号之间的值的字符串形式
return strOut; //返回对应的值,如id=123,则返回123
}
int main()
{
int s_begin = 0;
int s_end = 0;
int count = 0;
string strData = "id=tonyclare;exp=9532;id=sunny;exp=4214;id=simplle;exp=2134;id=tom;exp=23554;id=alex;exp=3554;";
count = getDatalength(strData); //获取字符串角色数量
//std::cout << count;
struct ROLE* pRole = new ROLE[count];
for (int i = 0; i < count; i++)
{
pRole[i].id = getneedstr("id",strData, s_begin, s_end);
pRole[i].exp = atoi(getneedstr("exp", strData, s_begin, s_end).c_str());
s_begin = s_begin + 3;
std::cout << pRole[i].id << " " << pRole[i].exp << std::endl;
}
system("pause");
return 0;
}
代码结果输出为
=tonyclare 0
=tonyclare 0
=tonyclare 0
=tonyclare 0
=tonyclare 0
而我想要的结果是
tonyclare 9532
sunny 4214
simplle 2134
tom 23554
alex 3554