gpt4 book ai didi

c++ - 重载 >> 运算符以读取文本文件

转载 作者:搜寻专家 更新时间:2023-10-31 00:00:11 26 4
gpt4 key购买 nike

使用此代码重载 >> 以读取文本文件:

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 通常不用于文件。
  • 您错过了流的返回。

事实上,您的运算符(operator)的更好版本是:

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;
};

此方法使您的代码更具 self 描述性:

if(myAlbum.load("albums.txt"))
// do stuff

关于c++ - 重载 >> 运算符以读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13859686/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com