gpt4 book ai didi

c++ - fstream文件读取失败

转载 作者:行者123 更新时间:2023-11-28 07:59:27 28 4
gpt4 key购买 nike

我想传递一个 fstream 对象并对单词进行标记。它总是打印 could not open file in hasNextToken() 。有人可以帮助我吗。

// main.cpp

int main() {
string filename = "input.txt";
fstream inputStream(filename);
Tokenizer t(inputStream);
while (t.hasNextToken()) {
cout << t.nextToken();
}
}

//分词器.h

class Tokenizer {
fstream fin;

public:
Tokenizer(fstream& file)
{
fin << file;
}

bool hasNextToken() {
if (!fin) {
cout << "Could not open file: " << endl;
exit(0);
}
return true;
}

string nextToken() {
string line;
getline(fin, line);
if (fin) {
istringstream sin(line);
string word;
sin >> word;
return word;

}
}
};

最佳答案

试试这个:

class Tokenizer {
fstream& fin;

public:
Tokenizer(fstream& file)
: fin(file)
{}

...
}

关于c++ - fstream文件读取失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11877120/

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