2014-12-06 157 views
-2

您好,我的教授發佈這個例子到她的網站舉例說明ifstreams,我怎麼不能打開任何.txt文件?文件不會打開ifstream

#include <iostream> 
#include <iomanip> // for setw 
#include <fstream> // for ifstream, ofstream 

using namespace std; 

int main() 
{ 
    char filename[25];  // a string for filename entry 

    int val;  // for reading integers from file 
    int sum = 0, count = 0;  
    double average; 

    ifstream in1;  // create an input file stream 

    do 
    { 
     in1.clear(); 
     cout << "Please enter the name of the input file.\n"; 
     cout << "Filename: "; 
     cin >> setw(25) >> filename; 

     in1.open(filename); 
     if (!in1) 
     cout << "That is not a valid file. Try again!\n"; 

    } while (!in1); 

    // PROCESS THE INPUT FILE 
    // Read all integer values and compute average 

    while (!in1.eof())  // while not end of file 
    { 
     in1 >> val;  // read an integer from file 

     if (!in1.fail())  // in case last call failed to read an int 
     {    // due to trailing white space at end of file 
    count++; 
     sum += val; 
     } 
    } 

    average = static_cast<double>(sum)/count; 

    cout << "There were " << count << " numbers in the file\n"; 
    cout << "Sum = " << sum << "\t\tAverage = " << average << "\n\n"; 

    in1.close(); 

    return 0; 
} 

這是非常加重的!這是我的電腦或其他問題嗎?

塊引用

+0

歡迎來到Stack Overflow!我們需要更多信息來幫助您 - 運行此代碼時發生了什麼? – Kelm 2014-12-06 23:42:31

+0

您是否嘗試過絕對路徑? – Borgleader 2014-12-06 23:44:14

+0

當我運行代碼時,它提示我輸入文件名,但它告訴我它永遠找不到我輸入的文件 – Demomomo 2014-12-06 23:44:32

回答

2

讓我做兩個假設:您使用的是一些IDE和您使用相對路徑。

IDE通常從不同於項目主目錄的目錄執行您的二進制文件。嘗試使用絕對路徑,找到正確的目錄或自己運行文件。

+0

我嘗試過使用絕對路徑,它仍然告訴我該文件不存在。此外,我正在使用Microsoft Visual Studio – Demomomo 2014-12-06 23:51:58

+0

您可以硬編碼代碼中的文件路徑,並告訴我它是否可以正常工作嗎? – Kelm 2014-12-06 23:55:07

+0

仍然無法正常工作:( – Demomomo 2014-12-07 00:02:18

0

你應該開始做的第一件事就是編寫代碼來理解錯誤。它現在是不是隻爲你,調試,同時也爲用戶以後,當他們都會遇到的問題:

.... 
    if (!in1) { // replace this bloc 
     cout << filename << " is not a valid file\n"; // print filename to find out any issues (truncated name, etc...) 
     cout << "Error code: " << strerror(errno)<<endl; // Get some system info as to why 
     char cwd[512];       // print current working directory. 
     getcwd(cwd, sizeof(cwd));    // in case your path is relative 
     cout << "Current directory is " << cwd << endl; 
     cout << "Try again !\n"; 
    } 

請注意:getcwd()作品在Linux下,但在Windows中,你將不得不使用_getcwd()代替。

重要提示:

下不會導致你的錯誤,但可能以後會出現問題:

while (!in1.eof()) {  // while not end of file 
     in1 >> val;   // read an integer from file 
     ... 

喜歡以下內容:

while (in1 >> val) {  // while read of file works 
     ... 

瀏覽角落找尋上SO:有很多問題/答案可以解釋原因。