我是 C++ 的新手,如果有明显的问题,我深表歉意。
我有一个正在读取的数据文件,它的信息格式为:
shapeName,Colour
,然后是点的坐标。我的 polyline
形状具有未知数量的坐标,但是当我尝试读取它们时,根本无法读取后面的任何形状。
这是主
polyline
循环中函数的 while
部分:
while(infile>>shapeName>>stringColour){
else if (shapeName == "Polyline"){
int XX,YY;
infile>>x1>>y1;//Read once and then set the values to the placeholder values in XX and YY
XX = x1;
YY = y1;
while(infile>>x2>>y2){
myLines.push_back(line(XX,YY,x2,y2));
x1 = x2; //Update the start point values
y1 = y2;
}
cout<<shapeName<<endl;
myShapes.push_back(make_unique<polyline>(polyline(colour,myLines)));
myLines.clear(); //clear the vector so it is ready for another polyline shape
}
}
有谁知道为什么运行这部分代码后主循环退出了?
我试过在某些地方使用
break
功能,但我看不到任何改进。我已经通过删除 polyline
形状确认这是问题所在,这导致以下形状被正确读取。
问题似乎出在您读取输入文件的方式上。当读取折线坐标的while循环结束时,输入流infile到达文件末尾,导致infile>>shapeName>>stringColour语句失败,退出while循环。要解决这个问题,您可以使用 clear() 函数清除文件结束标志,并在读取下一个形状名称和颜色之前使用 ignore() 函数忽略该行的其余部分。这是代码的更新版本:
while(infile>>shapeName>>stringColour){
if (shapeName == "Polyline"){
int XX,YY;
infile>>x1>>y1;//Read once and then set the values to the placeholder values in XX and YY
XX = x1;
YY = y1;
while(infile>>x2>>y2){
myLines.push_back(line(XX,YY,x2,y2));
x1 = x2; //Update the start point values
y1 = y2;
}
cout<<shapeName<<endl;
myShapes.push_back(make_unique<polyline>(polyline(colour,myLines)));
myLines.clear(); //clear the vector so it is ready for another polyline shape
infile.clear(); //clear the end-of-file flag
infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //ignore the rest of the line
}
}
这应该允许您读取输入文件中的所有形状而不会过早退出循环。