C++ C++;使用ofstream写入文件
我正在尝试使用ofstream()来写入文件(我正在编写一个汇编程序,将.asm文件转换为.hack文件,并将汇编命令转换为NandTotteris课程的二进制文件) 我在ofstream函数中遇到问题,以下是我的代码:C++ C++;使用ofstream写入文件,c++,file,input,ofstream,C++,File,Input,Ofstream,我正在尝试使用ofstream()来写入文件(我正在编写一个汇编程序,将.asm文件转换为.hack文件,并将汇编命令转换为NandTotteris课程的二进制文件) 我在ofstream函数中遇到问题,以下是我的代码: #include <stdio.h> #include <iostream> #include <fstream> using namespace std; bool replace(std::string& str, cons
#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();
}
#包括
#包括
#包括
使用名称空间std;
bool替换(std::string&str,const std::string&from,const std::string&to){
size\u t start\u pos=str.find(from);
if(start_pos==std::string::npos)
返回false;
str.replace(起始位置,从.length()到);
返回true;
}
int main(int argc,const char*argv[]
{
string file1=“hello.asm”;
在C++11之前,文件流类不接受std::string
文件名。因此,您可以传递一个C-string:
ofstream outfile(file1.c_str());
或者启用C++11,如果您当前的gcc版本支持它:
g++ -std=c++11 assembler.cpp
在C++11之前,文件流类不接受std::string
文件名。因此,您可以传递C-string:
ofstream outfile(file1.c_str());
或者启用C++11,如果您当前的gcc版本支持它:
g++ -std=c++11 assembler.cpp
顺便说一句,只是一个术语更正,ofstream
不是一个函数,它是一个类,在你的代码中,outfile
是这个类的一个对象。哦,我明白了,谢谢你的澄清。顺便说一句,只是一个术语更正,ofstream
不是一个函数,它是一个类,在你的代码中,outfile
是这个c的一个对象姑娘,哦,我明白了,谢谢你的澄清