子串和擦除
问题描述:
我想创建一个while循环,只要从文件中取出的字符串不是空的就运行。我需要用空格分隔字符串并保存信息以供将来使用,所以我将子字符串放入数组中,然后将其从实际数组中移除。但是,当我运行该程序时,我不断收到错误消息,或者只是打印出空白区域。 I added a picture of the file I'm using and of the error message I'm getting子串和擦除
fstream myfile;
string line;
string info[10000];
int i=0, pos;
myfile.open("bfine_project1_input.txt");
//Check
if (myfile.fail()){
cerr << "Error opening file" << endl;
exit(1);
}
if (myfile.is_open()){
while (getline (myfile,line)){
while(line.size() !=0){
pos = line.find(" ");
info[i]= line.substr(0,pos);
i++;
cout << info[i] << endl;
//line.erase(0, pos);
}
}
}
答
有两个问题我可以看到。
1 - 你增加“我”在打印之前(您存储在信息值[0]和打印信息[1])
2日 - 删除您使用不会删除空格“”的方式,所以find(“”)会从第二次向前返回位置0。
一些调整可以解决这个问题。请参阅下面的代码:
重要提示:您的代码写入方式需要在行末加空格!
string line;
string info[10000];
int i=0, pos;
line = "1325356 134 14351 5153613 1551 ";
while(line.size() !=0){
pos = line.find(" ");
info[i]= line.substr(0, pos);
cout << i << " " << info[i] << endl;
line.erase(0,pos+1); //ERASE " " too!
i++;//increment i only after everything is done!
}
是info' vector'?如果是这样,它的大小适当吗? – GWW
info是一个数组 – cdecaro
如何声明信息?我如何申报?我在哪里分配?你收到什么错误信息?为什么SO需要[mcve]? –