重载>>运算符以读取文本文件
Overloading >> operator to read in text file
有以下代码用于重载>>以读取文本文件:
std::istream& operator>> (std::istream &in, AlbumCollection &ac)
{
std::ifstream inf("albums.txt");
// If we couldn't open the input file stream for reading
if (!inf)
{
// Print an error and exit
std::cerr << "Uh oh, file could not be opened for reading!" << std::endl;
exit(1);
}
// While there's still stuff left to read
while (inf)
{
std::string strInput;
getline(inf, strInput);
in >> strInput;
}
调用者:
AlbumCollection al = AlbumCollection(albums);
cin >> al;
该文件位于源目录中,并且与.exe位于同一目录中,但它总是说它无法对文件进行精细化。抱歉,如果答案真的很明显,这是我第一次尝试在文本中读取C++文件;我真的不明白为什么这不起作用,我能找到的在线帮助似乎并不表明我做错了什么......
您必须检查工作目录。按相对路径指定文件时,始终将相对路径视为相对于工作目录的路径。例如,您可以使用函数 getcwd()
打印工作目录。
可以从 IDE 的项目属性更改设置中的工作目录。
一些评论:
- 不要从提取运算符退出。
- 您正在用
in
的内容覆盖inf
的内容。 -
cin
通常不适用于文件。 - 您错过了流的返回。
事实上,您的运算符的更好版本是:
std::istream& operator>>(std::istream& in, AlbumCollection& ac)
{
std::string str;
while(in >> str)
{
// Process the string, for example add it to the collection of albums
}
return in;
}
如何使用它:
AlbumCollection myAlbum = ...;
std::ifstream file("albums.txt");
file >> myAlbum;
但是对于序列化/反序列化,我认为最好的是使用AlbumCollection
中的函数:
class AlbumCollection
{
public:
// ...
bool load();
bool save() const;
};
此方法允许代码更具自描述性:
if(myAlbum.load("albums.txt"))
// do stuff
如果从 IDE 运行该程序,则可能是 IDE 的当前目录指向 exe 目录以外的其他位置。尝试从命令行运行 EXE。尝试提供文件的完整路径,以确保它可以找到它。
有点主题,虽然C++允许运算符重载,但我不鼓励这样做,原因很简单 - 这使得在代码中搜索运算符重载的声明变得困难!(尝试搜索特定类型的operator >>
...此外,具有go to declaration
功能的编辑器也不能很好地处理这个问题。最好是使其成为正常功能,
std::string AlbumsToString (AlbumCollection &ac)
它返回一个可以连接到流的string
:
mystream << blah << " " << blah << " " << AlbumsToString(myAlbums) << more_blah << endl; // !!!
您可以使用 AlbumToString
内部的 ostringstream
来构建类似字符串流的字符串,如果ostringstream
,则最终返回 str()
成员。
相关文章:
- 文本文件中的单词链表
- 从命令行c++发送文本文件名
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 如何创建一个QTableWidgetItem,用长文本右对齐,左边有省略号
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 从文本中抓取句子,将所有句子分别存储在某个数据结构中
- 从二进制文件中抓取文本时,为什么 xdg_vtnr=8 是我的结果
- C++ 中的列文本抓取
- Windows XP在C++中启动时读取文本文件的速度较慢;预取
- 从Windows应用程序的文本框中抓取文本