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

Overloading >> operator to read in text file

本文关键字:gt 取文本 文件 读取 运算符 重载      更新时间:2023-10-16

有以下代码用于重载>>以读取文本文件:

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() 成员。