【发布时间】:2019-02-15 23:24:11
【问题描述】:
我正在尝试实现一种从文本文件读取输入以更轻松地加载不同坐标集的方法,但我遇到了一个我不明白的错误,我的 stringstream 对象将停止接收字符串一旦其中一行格式错误。
在我的输出中,您可以看到打印出来的字符串仍然完好无损,然后将其放入下一行的stringstream,但在一个格式错误的字符串之后,stringstream 停止包含我打印出来的任何东西。
这里发生了什么?
输出:
这是文本文件的样子:
方法代码:
ifstream pathfile(p.string());
cout << "Path file opened successfully.\n\n";
string line;
stringstream ss;
int x, y;
char comma,direction;
//Iterate all lines in the file
while(getline(pathfile,line)){
//remove all spaces from line
line.erase(remove(line.begin(), line.end(), ' '), line.end());
//skip comments and blank lines
if(line.c_str()[0] == '#' || line.empty()) continue;
//parse remaining lines
ss.str(string()); //clear stringstream
cout <<"LINE: "<<line<<endl;
ss << line;
cout <<"SS: "<<ss.str()<<endl;
if(ss >> x >> comma >> y >> comma >> direction)
cout << "X: "<<x<<" Y: "<<y<<" D: "<<direction;
else{
cout << "Ill-formatted line: ";
}
printf(" | %s\n\n", line.c_str());
}
pathfile.close();
【问题讨论】:
-
line.c_str()[0]...嗯,为什么不line[0]?你应该检查它是否是一个空字符串 before 检查,而不是之后。
标签: c++ string c++11 ifstream stringstream