写入用户定义的 .txt 文件

writing in a user-defined .txt file

我用来写入 .txt 文件的基本语法是这样的:

ofstream myfile;
myfile.open ("data.txt", ios::trunc);
outfile<<"writing";

现在,假设我要让用户决定应该访问哪个文件,是否可以通过字符串来完成?

#include <iostream>
#include <fstream>
using namespace std;
int main (){
    ofstream myfile;
    string filename;
    char x;
    cin>>x;
    if (x==1)
        filename="data2.txt";
    myfile.open (filename, ios::trunc);
    myfile<<"writing";
    return 0;
}

我已经测试过了,但没有用。我的问题是:有可能做这样的事情吗?如果是,如何?当我编译它时,我得到的错误如下:

undefined reference to 'std::basicofstream<char, std::char_traits<char> >::open(std::string const&, std::_Ios_Openmode)'

我不明白是什么原因造成的。

您应该添加一个 else 分支,因为如果 x 不等于 1 open 没有可打开的内容。

您还忘记了在第二个代码段中声明 ofstream myfile;。也许这就是它不起作用的原因(它甚至不应该编译)。

您的错误提示找不到使用 std::string.

open 方法

试试这个:

myfile.open(filename.c_str(), ios::trunc);

某些版本的 C++ 不允许 std::string for open 方法,因此您将不得不使用 std::stringc_str() 方法。