2013-02-10 88 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; 
}