2015-03-08 60 views
0

我第一次嘗試C++,並認爲我會製作一個只打印文件中行的小程序。我使用的是Clion IDE,一切正常,工作正常。然後,在我的電腦死機的地方,當我嘗試再次運行代碼時,ifstream似乎沒有打開。下面的代碼:ifstream和ofstream在崩潰後不工作

#include <iostream> 
#include <fstream> 

using namespace std; 
    int main() { 
     ifstream file("hello.txt"); 
     cout << file.is_open() << endl; 
     string line; 
     while(getline(file, line)) cout << line << endl; 
     return 0; 
    } 

我試着重新安裝cygwin的(可能沒有正確地做這件事,不知道)和克利翁但沒有幫助。

編輯:嘗試通過網站編譯代碼,它的工作,但是當我在我的機器上運行它的文件無法打開。

編輯2:Clion在玩弄技巧並改變了工作目錄,設置完成後,一切正常。解決

+0

也許你沒有文件或其目錄的寫入權限。嘗試更改文件名和/或輸出失敗代碼('errno'可能有;否則調用'''GetLastError()')。代碼5表示拒絕訪問。 – 2015-03-08 19:28:41

+0

這是Clion玩弄我的技巧,它由於某種原因將工作目錄改爲NULL。現在修好了。 – Teo 2015-03-09 16:40:13

回答

-2
//Don't forget to include fstream 
    #include <fstream> 
    #include <iostream> 

    using namespace std; 

    int main() { 
     ifstream file("hello.txt"); 
    if(file.is_open()) 
    { 
    string line; 
    while(!file.eof()) //while we are not yet to the end of the file 
     { 
     getline(file, line) 
     cout << line << endl; 
     } 

    } 
    else 
     cout<<"File not opened \n"; 


    return 0; 
    } 
+0

我已經包含fstream,只忘了複製整個文件。 – Teo 2015-03-08 18:57:42

+0

'while(!file.eof())'是讀取文件的錯誤方法。 'getline'應該在'while'中。 – 2015-03-08 19:14:54

+0

'file.eof()'並不意味着「我們在文件的末尾」 – 2015-03-08 19:29:46