C++ using ofstream to write to file -


i trying use ofstream() write file (i writing assembler converts .asm file .hack file , converts assembly commands binary nandtotetris course)

i having trouble ofstream function, here code:

#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 error:

g++ assembler.cpp assembler.cpp: in function ‘int main(int, const char**)’: assembler.cpp:23: error: no matching function call ‘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, file stream classes did not accept std::string file names. can either pass c-string:

ofstream outfile(file1.c_str()); 

or enable c++11, if current gcc version supports it:

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

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -