【问题标题】:writing to a file with an uncertain filename [closed]写入文件名不确定的文件[关闭]
【发布时间】:2014-03-25 10:40:13
【问题描述】:

我给了一个任务,我需要从一个名为“filename.s”的文件中获取一些输入,我的代码应该将输出写入一个名为“filename.m”的文件。这是我的代码,但是当我尝试以 outfile.open(out); 身份打开文件时遇到编译问题

int main(int argc, char *argv[]){
  readFile(argv);
  int x=0;
  compile(x);
  mystring += "halt";
  cout << mystring<< endl;
  string out = argv[1];
  out.resize(out.size()-1);
  out += "m";
  ofstream outfile;
  outfile.open(out);
  outfile << mystring;
  outfile.close();
  return 0;
}

有人知道可能是什么问题吗?因为当我给出这样的论点时它会编译:outfile.open("blah.m");thanks for your reply.

【问题讨论】:

  • 我建议您先编辑代码并添加所有变量的声明。
  • 你的意思是你有编译错误?在这种情况下,您应该编辑您的问题以包含完整且未经编辑的错误日志。

标签: c++ file input output ofstream


【解决方案1】:

我猜你使用的是没有 C++11 的旧编译器,所以行

outfile.open(out);

编译失败,因为 ni C++98 open 只接受字符指针而不接受 std::strings。将行改为

outfile.open(out.c_str());

它应该编译

【讨论】:

  • 工作。谢谢!另外,你知道如何将 ubuntu 13.10 中的 g++ 更新为 c++11 吗?
  • @AtakanArıkan 你添加了标志-std=c++11
【解决方案2】:

试试这个:

outfile.open(out.c_str());

在C++98中,open()的参数是const char *

【讨论】:

    【解决方案3】:

    更简单的解决方案,但针对这种情况:

    size_t pos = strlen(argv[1]) - 1;
    argv[1][pos] = 'm';
    
    std::ofstream out(argv[1]); // Easier to just create the stream already opened.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2013-10-31
      • 2013-03-29
      • 2020-09-06
      相关资源
      最近更新 更多