更改变量目录的.txt文件

rec*_*gle 1 c++ text-files

我正在尝试编写一个改变变量目录的.txt文件的程序.但是,当我尝试这样做时,我收到一个错误.

我的错误:

no matching function for call to `std::basic_ofstream<char,      std::char_traits<char> >::basic_ofstream(std::string&)' 
Run Code Online (Sandbox Code Playgroud)

我的代码:

#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;

}
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Jam*_*lis 6

fstream构造带C字符串,不是std::string,所以你需要

std::ofstream myfile(file_name.c_str());
Run Code Online (Sandbox Code Playgroud)

他们采用C字符串代替std::strings的原因纯粹是历史性的; 没有技术原因.C++ 0x添加了带std::strings的构造函数.