如何使用 ifstream 打开文件并继续读取直到最后

How to open a file using ifstream and keep reading it until the end

本文关键字:继续 读取 直到最后 文件 何使用 ifstream      更新时间:2023-10-16

我只想打开一个名为"test.txt"的文件,其中包含:

cat
dog
moose
rabbit

然后,我想从文件中读取并将其内容转换为字符串,以便稍后在程序中执行的操作。 到目前为止,我认为我正在做的事情正朝着正确的方向发展。 但是,我收到错误,我不确定该怎么办。 这是错误>>>

$ make -f makefile.txt
g++ -g -D HASH_TABLE_SIZE=10 -c hash.cpp
hash.cpp: In member function `void Hash::processFile(std::string)':
hash.cpp:12: error: no match for 'operator>>' in 'my_infile >> word'
makefile.txt:6: recipe for target `hash.o' failed
make: *** [hash.o] Error 1

这是我到目前为止的代码(因此它不会编译)

void Hash::processFile(string filename)
{
    string word;
    Hash HashTable;
    ifstream my_infile(const char* filename, ios_base::openmode mode = ios_base::in);
    while(my_infile >> word)//iterate through the file and hash them (handles collisions too)
    {
        //Insert keys and handle collisions
    }
}
ifstream my_infile(const char* filename, ios_base::openmode mode = ios_base::in);

该行不是在创建std::ifstream的实例,而是在声明一个函数。

您需要该行是:

ifstream my_infile(filename);