视觉C++ 尝试重载 ifstream 以将文件读入类的数组
visual C++ Trying to Overload ifstream to read file into a Class's array
我试图重载ifstream操作符>>,以便从文本文件中读取数据,并将数据放在属于State的类中。
我正在读取的文件格式是州名>州首府>人口。我只是想把状态名读入数组。
我一直遇到操作符重载的问题。我有点理解它,并能够使ostream工作,但阅读已被证明是更困难的。
不确定这是否有影响,但这是学校的作业,我还在做。只是不知道该往哪里走。
main.cpp
这是我的主CPP文件。
#include <iostream>
#include <string>
#include <fstream>
#include "State.h"
using namespace std;
int main(){
State s, h;
string null;
ifstream fin("states.txt");
while(fin.good())
{
fin >> h; //This doesn't read anything in.
fin >> null; //Dumping the Capital City to a null string
fin >> null; //Dumping the Population to a null string
}
cout << s; //Testing my overloaded << operator
system("pause");
return 0;
}
State.cpp
这是一个次要CPP文件。
#include "State.h"
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int i = 0;
string name, x, y;
State::State()
{
arrayStates[50];
}
//Trying to overload the input from fstream
ifstream& operator >> (ifstream& in, State h)
{
for(i = 0; i < 21; i++)
{
in >> h.arrayStates[i];
}
return in;
}
ostream& operator << (ostream& out, State s)
{
for(int i = 0; i < 21; i++)
{
out << s.arrayStates[i] << endl;
}
return out;
}
State.h
这是包含类的头文件。
#include <iostream>
#include <string>
using namespace std;
class State{
private:
string arrayStates[50];
public:
State();
friend ostream& operator << (ostream& out, State s);
friend ifstream& operator >> (ifstream& in, State h);
};
错误在此函数中,如您所建议的。
ifstream& operator >> (ifstream& in, State h)
{
for(i = 0; i < 21; i++)
{
in >> h.arrayStates[i];
}
return in;
}
该函数生成State
的临时副本,调用该副本h
,并初始化该副本。
通过引用传递原State
。所以它指的是指向同一个对象。
ifstream& operator >> (ifstream& in, const State &h)
相关文章:
- 如何将内容数组写入文本文件?
- C++将文本文件中的数据读取到结构数组中
- 将值从二维数组输出到文本文件
- C++数据文件、数组和计算赋值
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何从txt文件中读取多个不同长度的数组?
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- C++编程从外部文本文件定义数组大小
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 如何将文本文件的特定行读取到 int 类型的数组中C++?
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 将系数存储在头文件的数组中("does not name a type"错误)
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 从文件读取,并写入函数C++中的数组
- 如何使用QJSONARRAY在QT5(C )中解析JSON文件(数组)
- 从文件/数组C++聚合数据