我想传递一个 fstream 对象并对单词进行标记。它总是会打印无法打开的文件hasNextToken()
。愿有人帮助我。
//main.cpp
int main() {
string filename = "input.txt";
fstream inputStream(filename);
Tokenizer t(inputStream);
while (t.hasNextToken()) {
cout << t.nextToken();
}
}
//Tokenizer.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;
}
}
};