文件不会打开ifstream

时间:2014-12-06 23:40:57

标签: c++ ifstream

您好我的教授将此示例发布到她的网站上,给出了ifstreams的示例,为什么我无法打开任何.txt文件?

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

这非常恶化!这是我的电脑有问题吗?

块引用

2 个答案:

答案 0 :(得分:2)

让我做两个假设:你正在使用一些IDE而你正在使用相对路径。

IDE通常从不同于项目主目录的目录中执行二进制文件。尝试使用绝对路径,找到正确的目录或自己运行文件。

答案 1 :(得分: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上浏览arround:有很多问题/答案可以解释原因。