2013-02-10 69 views
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(); 
+0

什么是文件的内容和你的输出是什么? – 2013-02-10 15:54:40

+0

这和Xcode有什么关系? – 2013-02-10 15:54:49

+1

尝试打印'x'来查看它是否读取任何内容。 – jrok 2013-02-10 15:59:09

回答

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; 
}