下面是我的代码
ifstream& operator>>(ifstream &input,Line3D &line3d)
{
int x1,y1,z1,x2,y2,z2;
x1=0;
y1=0;
z1=0;
x2=0;
y2=0;
z2=0;
//get x1
input.ignore(2);
input>>x1;
//get y1
input.ignore();
input>>y1;
//get z1
input.ignore();
input>>z1;
//get x2
input.ignore(4);
input>>x2;
//get y2
input.ignore();
input>>y2;
//get z2
input.ignore();
input>>z2;
input.ignore(2);
//cout << x1 << "," << y1 << "," << z1 << "," <<endl;
//cout << x2 << "," << y2 << "," << z2 << "," <<endl;
Point3D pt1(x1,y1,z1);
Point3D pt2(x2,y2,z2);
line3d.setPt1(pt1);
line3d.setPt2(pt2);
line3d.setLength();
}
有这个奇怪的问题,如果我评论我的cout,上面的2个cout。我的代码不起作用,但如果我取消注释它,代码将工作..继承人终端输出..
Please enter your choice: 1
Please enter filename: messy.txt
10 records read in successfully!
Going back to main menu ...
但如果我取消评论cout ......
请输入您的选择:1
Please enter filename: file.txt
7,12,3,
-9,13,68,
7,-12,3,
9,13,68,
70,-120,-3,
-29,1,268,
25,-69,-33,
-2,-41,58,
9 records read in successfully!
Going back to main menu ...
9记录是正确的。但为什么一个cout会解决我的代码问题。虽然我认为cout只是打印到终端。我在这里做错了什么。
这是文本文件内容
Point2D, [3, 2]
Line3D, [7, 12, 3], [-9, 13, 68]
Point3D, [1, 3, 8]
Line2D, [5, 7], [3, 8]
Point2D, [3, 2]
Line3D, [7, -12, 3], [9, 13, 68]
Point3D, [6, 9, 5]
Point2D, [2, 2]
Line3D, [70, -120, -3], [-29, 1, 268]
Line3D, [25, -69, -33], [-2, -41, 58]
Point3D, [6, 9, -50]
我想从终端获得的正确答案是
Correct output: 9 records read in successfully
Reason: as 10 means the value fail to record to vector. and duplicate is not removed.
感谢所有指南,我该怎么做才能保持正确的输出,然后移除cout ..
我在main.cpp上的更多代码:
readFile.open(filename.c_str());
//if successfully open
if(readFile.is_open())
{
//record counter set to 0
numberOfRecords = 0;
while(readFile.good())
{
//input stream get line by line
readFile.getline(buffer,25,',');
Line3D line3d_tmp;
readFile>>line3d_tmp;
done=true;
//some for loop to check for duplication
//done will be false if doesnt work
if(done==true)
{
line3d.push_back(line3d_tmp);
}
所以你看看值是否是push_back进入我的向量,重复的记录将被删除,因为我故意把2个相同值的记录。问题是如果我使用2 cout线。记录显示为9(正确为1行重复),第二次运行时输入相同文件。正在阅读0条记录..
但是,如果我在第二次运行中评论我的cout,它会再次读取4个RECORDS。第一次运行是10条记录..
答案 0 :(得分:1)
有几点:
ifstream
更改为istream
input
operator>>()
定义Point3D
并在Line3D