0

我想从文件中读取每个单词。它打开文件但没有进入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();
4

1 回答 1

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;
}
于 2013-02-10T17:10:49.797 回答