在C++中取消设置变量时,文件打开(ifstream)不正确

Incorrect file opening (ifstream) when unsetting a variable in C++

本文关键字:ifstream 不正确 文件 C++ 取消 设置 变量      更新时间:2023-10-16

我有以下C++程序。我打开一个文件(inputmincut.txt)并读取其内容。每当我评论n=0行时,程序就会崩溃。这对我来说毫无意义。会发生什么?

using namespace std;
ifstream input_file;
ofstream output_file;
int n;
  void read()
    {
     int current=0; 
     int pos=0; 
     for(int i=1;i<=n;i++)
      { 
       input_file>>current;
       input_file>>pos;      
       while(pos!=-1)
        input_file>>pos;                          
      }        
     }  

int main(int argc, char *argv[])
{

    input_file.open("C:\Dev-Cpp\inputmincut.txt");
     input_file>>n;
     read();
     input_file.close();
     //n=0;
     input_file.open("C:\Dev-Cpp\inputmincut.txt");
     input_file>>n;
     read();
     input_file.close();

    system("PAUSE");
    return 0;
}

这是文本输入。

101 2 10-12 3 1-13 4 2-14 5 3-15 6 4-16 7 5-17 8 6-18 9 7-19 10 8-110 1 9-1

input_file.open("C:\Dev-Cpp\inputmincut.txt");

您确定在操作系统中使用"\"而不是""来表示路径吗!我认为你应该检查你的文件路径,并检查你是否打开了你的文件?

首先,您必须检查文件是否打开以进行读取。你可以写这样的东西:

void ropen(std::string const & path, std::ifstream & file)
{
    file.open(path.c_str(), std::ios_base::in|std::ios_base::binary);
    if(!file.is_open()) throw std::exception(
        path +
        std::string(": cannot open file for reading.")
    );
}

然后:

int main(int argc, char *argv[])
{
  std::istream file;
  ropen(path,file);
  std::line;
  while(getline(file, line))
  {
    do something with your line
  }
  return 0;
}