不读文件

时间:2013-02-10 15:53:54

标签: c++

我想从文件中读取每个单词。它会打开文件,但不会进入while循环

  string x;
        ifstream inFile ("test.txt");
        if (!inFile) {
            cout << "Unable to open file";
            exit(1); // terminate with error
        }

        while (inFile >> x) {
            cout << "hi" << endl;
        }
        cout << "hsiwsdsc" << endl;

        inFile.close();

1 个答案:

答案 0 :(得分:0)

我的朋友,你没有检查文件是否打开。看看这段代码:

#include <string>

int main(int argc, char** argv) {
    std::string line;
    std::ifstream input("example.txt");

    if (input.is_open()) {
        while (input.good()) {
            std::getline(input, line);
            std::cout << line << std::endl;
        }
    } else {
        std::cerr << "Unable to open stinky file" << std::endl;
    }

    return 0;
}