0

下面是我的代码

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 条记录。第一次运行是 10 条记录。

4

1 回答 1

1

几点:

  • 更改ifstreamistream
  • input在运算符末尾返回
  • 定义一个operator>>()forPoint3D并将其用于Line3D
于 2012-11-15T10:18:28.483 回答