【问题标题】:C++ using ofstream to write to fileC++ 使用 ofstream 写入文件
【发布时间】:2015-05-30 14:50:07
【问题描述】:

我正在尝试使用 ofstream() 写入文件(我正在编写一个汇编程序,将 .asm 文件转换为 .hack 文件并将汇编命令转换为 NANDTOTETRIS 课程的二进制文件)

我在使用 ofstream 函数时遇到问题,这是我的代码:

#include <stdio.h>
#include <iostream>
#include <fstream>

using namespace std;


bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}

int main( int argc, const char* argv[] )
{
    string file1 = "hello.asm";
    cout << "before: " << file1 << endl;
    replace(file1, "asm", "hack");
    cout << "after: " << file1 << endl;

    ofstream outfile(file1);
    outfile << "my text here!" << std::endl;
    outfile.close();

}

这是我的错误:

g++ assembler.cpp
assembler.cpp: In function ‘int main(int, const char**)’:
assembler.cpp:23: error: no matching function for call to ‘std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::string&)’
/usr/lib/gcc/i686-redhat-linux/4.4.7/../../../../include/c++/4.4.7/fstream:623: note: candidates are: std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-redhat-linux/4.4.7/../../../../include/c++/4.4.7/fstream:608: note:                 std::basic_ofstream<_CharT, _Traits>::basic_ofstream() [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-redhat-linux/4.4.7/../../../../include/c++/4.4.7/iosfwd:84: note:                 std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(const std::basic_ofstream<char, std::char_traits<char> >&)
[a1649446@ingb16w013 projects]$ 

【问题讨论】:

  • 顺便说一句,只是术语更正,ofstream 不是一个函数,它是一个类,在您的代码中,outfile 是该类的一个对象。
  • 哦,我明白了,感谢您的澄清

标签: c++ file input ofstream


【解决方案1】:

在 C++11 之前,文件流类不接受 std::string 文件名。所以你可以传递一个 c 字符串:

ofstream outfile(file1.c_str());

或者启用 C++11,如果你当前的 gcc 版本支持它:

g++ -std=c++11 assembler.cpp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2012-05-14
    • 1970-01-01
    相关资源
    最近更新 更多