基本上我想做的就是阅读每行,根据点将其分开,打印每个团队的名称,对于团队中的每个成员,我都希望打印出他们的名称和其他整数。我的代码是这样的:
int main () {
int x;
int y;
int j;
int t;
const char* pos;
const char* nam;
const char* line;
vector<const char*> v;
string str;
ifstream myfile ("data.txt");//opens file
if (myfile.is_open())//if you can open the file
{
while ( getline (myfile,str,'.') )//reads each line and breakes it apart based on the '.'
{
line=str.c_str();
v.push_back(line);//puts each field in a vector
}
myfile.close();
const char* lim="Team Name";
const char* name=v[1];
cout<<"team one"<<name<<endl;
int i=2;
while((i<v.size())&&(v[i]!=lim)){//adds the players for the first team
pos=v[i];
i++;
nam=v[i];
i++;
x=atoi(v[i]);//gets the x position from string to int
i++;
y=atoi(v[i]);//gets the y position from string to int
i++;
j=atoi(v[i]);//gets the jnum position from string to int
i++;
t=atoi(v[i]);//gets the targetline position from string to int
cout<<"position: "<<pos<<" name: "<<nam<<" x: "<<x<<" y: "<<y<<" jnum: "<<j<<" targ: "<<t<<endl;
i++;
}
i++;
const char* name2=v[i];
cout<<"team two"<<name2<<endl;
i++;
lim="end";
while((i<v.size())&&(v[i]!=lim)){//adds the players for the second team
pos=v[i];
i++;
nam=v[i];
i++;
x=atoi(v[i]);//gets the x position from string to int
i++;
y=atoi(v[i]);//gets the y position from string to int
i++;
j=atoi(v[i]);//gets the jnum position from string to int
i++;
t=atoi(v[i]);//gets the targetline position from string to int
cout<<"position: "<<pos<<" name: "<<nam<<" x: "<<x<<" y: "<<y<<" jnum: "<<j<<" targ: "<<t<<endl;
i++;
}
return 0;
}
}
但是我的代码无法正确读取所有内容,最后它为每个const char *打印一个空格,为每个int打印0。我之前用字符串而不是const char *尝试了与此类似的代码,它可以工作,但是program.exe在读取和打印数据后停止工作。有了这个方法,program.exe不会停止工作,但是就像我提到的那样,它不能正常工作。有人对此有解决方案吗?
在此while
:
while (getline(myfile,str,'.'))//reads each line and breakes it apart based on the '.'
{
line=str.c_str();
v.push_back(line);//puts each field in a vector
}
您设置指针变量const char* line
。但是它包含从中获得str
的地址,每次都可能从中获得相同的地址。
因此,您最终得到所有指向(可能)同一事物的指针向量。
每次读取文件中的新字符串时,它不会每次更改吗?
它指向的值确实会更改,但是不能保证编译器将使用新的指针。实际上,当str
超出范围时,我们现在有了一个不能保证存在的指针。我们正处于不确定行为的火车上,这是您不想参加的火车。至少在此程序中str
仍然存在范围,但是这种方法很容易出错。
如果没有,我如何能够每次更新它?
将的每个实例替换为const char*
,std::string
并c_str()
在需要时使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句