Alter a .txt file of a variable directory
I'm trying to write a program that alters a .txt file of a variable directory. However开发者_开发技巧 when I attempt to do so I get an error.
My error:
no matching function for call to `std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::string&)'
My code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string file_name ;
cout << "Input the directory of the file you would like to alter:" << endl;
cin >> file_name ;
ofstream myfile ( file_name );
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
What did I do wrong?
The fstream
constructors take C strings, not std::string
, so you need
std::ofstream myfile(file_name.c_str());
The reason why they take C strings instead of std::string
s is purely historical; there's no technical reason. C++0x adds constructors that take std::string
s.
精彩评论