写入用户定义的.txt文件

writing in a user-defined .txt file

本文关键字:txt 文件 定义 用户      更新时间:2023-10-16

我用来写入。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)'

我不明白是什么引起的

您的错误提示无法找到使用std::stringopen方法。

试试这个:

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

某些版本的c++不允许std::string for open方法,所以你将不得不使用std::stringc_str()方法。

你应该添加一个else分支,因为如果x不等于1, open没有什么可打开的

您还忘记在第二个代码片段中声明ofstream myfile;。也许这就是为什么它不能工作(它甚至不应该编译)。