gpt4 book ai didi

C++使用ofstream写入文件

转载 作者:行者123 更新时间:2023-11-27 22:58:09 25 4
gpt4 key购买 nike

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

我在使用 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]$

最佳答案

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

ofstream outfile(file1.c_str());

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

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

关于C++使用ofstream写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30547544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com