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
中使用
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- C++InStream过载问题