The*_*ral 2 c++ io overloading
有这个代码重载>>来读取文本文件:
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;
}
Run Code Online (Sandbox Code Playgroud)
被称为:
AlbumCollection al = AlbumCollection(albums);
cin >> al;
Run Code Online (Sandbox Code Playgroud)
该文件位于源目录中,与.exe位于同一目录中,但始终表示文件无法正常处理.很抱歉,如果答案非常明显,这是我第一次尝试用C++读取文本文件; 我真的不明白为什么这不起作用,我能找到的在线帮助似乎并没有表明我做错了什么....
你必须检查工作目录.通过其相对路径指定文件时,相对路径始终被视为相对于工作目录.例如,您可以使用该功能打印工作目录getcwd().
您可以从IDE的项目属性更改设置中的工作目录.
一些评论:
inf的内容in.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;
}
Run Code Online (Sandbox Code Playgroud)
如何使用它:
AlbumCollection myAlbum = ...;
std::ifstream file("albums.txt");
file >> myAlbum;
Run Code Online (Sandbox Code Playgroud)
但是对于序列化/反序列化,我认为最好使用以下函数AlbumCollection:
class AlbumCollection
{
public:
// ...
bool load();
bool save() const;
};
Run Code Online (Sandbox Code Playgroud)
此方法允许您的代码更具自我描述性:
if(myAlbum.load("albums.txt"))
// do stuff
Run Code Online (Sandbox Code Playgroud)