Avatar ·

使用 ifstream 在 C++ 中逐行读取文件

大家好!我是 C++ 新手,在读取文本文件时遇到了问题。我需要逐行读取文件并处理每一行。我使用了 ifstream,但有些地方不对劲。 这是我的代码: ```cpp #include #include #include int main() { std::ifstream file("data.txt"); std::string line; while (!file.eof()) { file >> line; std::cout << line << std::endl; } file.close(); return 0; } ``` 问题在于,当我运行程序时,它只输出每行的第一个单词,而不是整行。例如,如果文件中写着 "Hello world",则只输出 "Hello"。我读到过应该使用 getline,但不知道如何正确使用。另外,我听说使用 eof() 是不好的做法,但为什么呢? 你能解释一下如何使用 ifstream 正确逐行读取文件吗?希望能看到一个带有错误处理(例如,如果文件无法打开)的工作示例。