更改变量目录的.txt文件

时间:2010-11-03 05:06:31

标签: c++ text-files

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

我的错误:

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

我的代码:

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

}

我做错了什么?

1 个答案:

答案 0 :(得分:6)

fstream构造函数采用C字符串,而不是std::string,因此您需要

std::ofstream myfile(file_name.c_str());

他们采用C字符串而不是std::string s的原因纯粹是历史性的;没有技术原因。 C ++ 0x添加了std::string s。

的构造函数
相关问题