c++ - 写入用户定义的 .txt 文件

标签 c++ gcc windows-7

我用来写入 .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 用于 open 方法,因此您必须使用 c_str() std::string 的方法。

关于c++ - 写入用户定义的 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32977872/

相关文章:

c - 将 .a 库链接到 .o 对象,因此在构建时只需要包含 .o

javascript - 我可以在 IIS 上从 "Classic"ASP 生成 JSON 吗?

windows - Sublime 作为默认编辑器

c++ - 您如何获得程序使用了多少内存?

c++ - 什么 API 会启动 FTP 传输并向 GUI 报告状态?

c++ - 检查整数类型

c - 这是拦截系统调用的好方法吗?

c++ - 可变参数模板构造函数的推导指南失败

c++ - 如何在Windows中模拟注册表进行程序测试?

python - Windows 7/Vista 进程管理 - 如何在长时间空闲后启动外部程序?