程序正在编译和运行,但不工作

Program compiling and running, but not working?

本文关键字:工作 运行 编译 程序      更新时间:2023-10-16

我对这段代码有一些问题,得到了一些帮助,它工作得很好。继续进行一些调整,现在程序编译并运行了,但它没有做它应该做的事情(接受一个c++文件,删除注释,并打印出一个新文件)。它不是打印一个新文件…知道我搞砸了什么吗?

#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>
using namespace std;
void remove_comments (ifstream& , ofstream&);
int main(void)
{
  int i;
  string inputFileName;
  string outputFileName;
  string s;
  ifstream fileIn;
  ofstream fileOut;
  char ch;
  do
  {
    cout<<"Enter the input file name:";
    cin>>inputFileName;
  }
  while (fileIn.fail() );
  cout<<"Enter the output file name: ";
  cin>>outputFileName;
  fileIn.open(inputFileName.data());
  assert(fileIn.is_open() );
  remove_comments ( fileIn , fileOut);         
  fileIn.close();
  fileOut.close();
  return 0;
}

void remove_comments( ifstream& fileIn , ofstream& fileOut)
{
  string line;
  bool flag = false;
  while (! fileIn.eof() )
  {
    getline(fileIn, line);
    if (line.find("/*") < line.length() )
      flag = true;
    if (! flag)
    {
      for (int i=0; i < line.length(); i++)
      {
        if(i<line.length())
          if ((line.at(i) == '/') && (line.at(i + 1) == '/'))
          break;
          else
            fileOut << line[i];
      }
      fileOut<<endl;

  }
  if(flag)
  {
    if(line.find("*/") < line.length() )
      flag = false;
  }
}
}

您忘记使用std::ofstream::open:

打开输出流文件
fileOut.open(outputFileName);

还注意到std::ifstreamopen有一个重载,它通过常量引用std::string,因此:

fileIn.open(inputFileName.data());

可以成为:

 fileIn.open(inputFileName);

为什么不能从命令行获取参数?

那就简单多了。

void remove_comments (ifstream& , ofstream&);
int main(int argc, char** argv)
{
  if(argc!=3){
    cerr<<"usage: "<<argv[0]<<" input.file output.filen";
    return -1;
  }
  int i;
  string inputFileName=argv[1];
  string outputFileName=argv[2];
  string s;
  ifstream fileIn(inputFileName.c_str());
  if(!fileIn.is_open()){
     cerr<<"error opening input filen";
     return -1; 
  }
  ofstream fileOut(outputFileName.c_str());
  if(!fileOut.is_open()){
     cerr<<"error opening Output filen";
     return -1; 
  }
  remove_comments ( fileIn , fileOut);       
  return 0;
}
相关文章: