Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 更改变量目录的.txt文件_C++_Text Files - Fatal编程技术网

C++ 更改变量目录的.txt文件

C++ 更改变量目录的.txt文件,c++,text-files,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>

我正试图编写一个程序,改变一个变量目录的.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;

}
我做错了什么

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

std::ofstream myfile(file_name.c_str());
他们采用C字符串而不是std::字符串的原因纯粹是历史原因;没有技术上的原因。C++0x添加采用std::string的构造函数。

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

std::ofstream myfile(file_name.c_str());
他们采用C字符串而不是std::字符串的原因纯粹是历史原因;没有技术上的原因。C++0x添加接受std::strings的构造函数。

您不必调用myfile.close;ofstream析构函数将自动为您关闭该文件。当您像使用cin>>文件名一样从流中读取输入时,应始终检查以确保输入成功。当您读入字符串时,操作不太可能会失败,但如果您读入其他内容(如某种数字),则更可能失败;ofstream析构函数将自动为您关闭该文件。当您像使用cin>>文件名一样从流中读取输入时,应始终检查以确保输入成功。当您读入一个字符串时,操作不太可能失败,但是如果您读入其他内容,比如某种数字,则失败的可能性更大。