C++InStream过载问题

C++ InStream Overload Issue

本文关键字:问题 C++InStream      更新时间:2023-10-16

下面是我的代码

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);
}

因此,您可以看到,如果值被推回到我的向量中,那么重复的记录将被删除,因为我故意放置了两个相同值的记录。问题是如果我使用2 cout行。记录显示为9(更正为有1行重复),并在第二次运行时输入相同的文件。正在读取0条记录。。

但如果我评论掉我的cout,在第二次运行时,它会再次读取4条记录。第一轮是10张唱片。。

几点:

  • ifstream更改为istream
  • 在运算符末尾返回input
  • Point3D定义一个operator>>(),并在Line3D中使用