有关重载用于读取文本文件的输入运算符>>的问题
Problems regarding Overloading the input operator >> for reading text file
我有一个Point2D
类,我正在尝试重载输入运算符>>
class Point2D
{
public:
Point2D(int,int);
int getX();
int getY();
void setX(int);
void setY(int);
double getScalarValue();
bool operator < ( const Point2D& x2) const
{
return x < x2.x;
}
friend istream& operator >> (istream&,Point2D);
protected:
int x;
int y;
double distFrOrigin;
void setDistFrOrigin();
};
在我的主要功能之外
#include <iostream>
#include <fstream>
#include "Line2D.h"
#include "MyTemplates.h"
#include <string>
#include <set>
using namespace std;
istream operator >> (istream& is , Point2D p2d)
{
string p;
getline(is,p,'n');
int position = p.find(", ");
string k = p.substr(0,position);
if ( k == "Point2D")
{
string x = p.substr(10,1);
int x_coordinate = atoi(x.c_str()); // atoi(x.c_str()) convert string x to int
p2d.setX(x_coordinate);
}
return is;
}
在我的 int main() 中
int main()
{
fstream afile;
string p;
afile.open("Messy.txt",ios::in);
if (!afile)
{
cout<<"File could not be opened for reading";
exit(-1);
}
Point2D abc;
afile>>abc;
set<Point2D> P2D;
P2D.insert(abc);
set<Point2D>::iterator p2 = P2D.begin();
while ( p2 != P2D.end() )
{
cout<<p2->getX();
p2++;
}
}
我不明白为什么我会收到错误:
C++ 禁止声明没有类型的 ISTREAM
我已经使用命名空间std包含了iostream,fstream,我不知道出了什么问题
您的代码中有几个问题。
-
这是出现错误消息的原因。你不会
#include <iostream>
Point2D.h
/Line2D.h
.正如其他人已经建议的那样,使用
std::istream
而不仅仅是istream
。 -
正确的
operator>>()
应该是std::istream &operator>>(std::istream &is, Point2D &p2d);
请注意
std::istream&
和Point2D&
。Point2D&
很重要,因为否则您修改本地副本并且给定的参数保持不变。 -
您的输入运算符很脆弱。它容易受到或多或少的空格的影响。您还允许
x_coordinate
的正好一位数字。此外,您跳过一个字符超出Point2D,
.更好的方法是只用空格分隔部分,让 iostream 库处理解析。例如Point2D 15 28
可以由
string tag; is >> tag; if (tag == "Point2D") is >> p2d.x >> p2d.y; return is,
弹出
的东西(正如 Dietmar Kühl 提到的)是你没有返回 istream 的引用。尝试更改此方法标头
istream operator >> (istream& is , Point2D p2d)
对此:
istream& operator >> (istream& is , Point2D p2d)
根据经验,返回对尚未为其创建复制构造函数的对象的引用通常是一个好主意。返回引用意味着返回对象所在的地址。要按值正确返回,需要对要返回的对象进行复制。
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type