简体   繁体   English

C ++使用ofstream写入文件

[英]C++ using ofstream to write to file

I am trying to use ofstream() to write to a file (I am writing an assembler that converts .asm file into .hack file and converts assembly commands into binary for the NANDTOTETRIS course) 我正在尝试使用ofstream()写入文件(我正在编写将NANDTOTETRIS课程将.asm文件转换为.hack文件并将汇编命令转换为二进制文件的汇编程序)

I am having trouble with the ofstream function, here is my code: 我在使用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();

}

And this is my error: 这是我的错误:

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]$ 

Before C++11, the file stream classes did not accept std::string file names. 在C ++ 11之前,文件流类不接受std::string文件名。 So you can either pass a c-string: 因此,您可以传递一个c字符串:

ofstream outfile(file1.c_str());

Or enable C++11, if your current gcc version supports it: 或启用C ++ 11(如果您当前的gcc版本支持它):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM