写入用户定义的.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)'
我不明白是什么引起的
您的错误提示无法找到使用std::string
的open
方法。
试试这个:
myfile.open(filename.c_str(), ios::trunc);
某些版本的c++不允许std::string
for open
方法,所以你将不得不使用std::string
的c_str()
方法。
你应该添加一个else
分支,因为如果x
不等于1
, open
没有什么可打开的
您还忘记在第二个代码片段中声明ofstream myfile;
。也许这就是为什么它不能工作(它甚至不应该编译)。
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 无法打开.txt文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 使用fstream对txt文件中的数字进行循环
- Visual Studio在尝试读取resource.txt文件时崩溃
- 如何从txt文件中读取多个不同长度的数组?
- 在一次迭代中从 txt 文件中读取多行
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 写入超过 1GB 的.txt文件时出现奇怪的行为
- 视觉 如何循环访问C++中遵循类似格式的多个.txt文件?
- txt 文件中浮点数的最大和最小值
- 从.txt文件中读取浮点型数字并在公式中使用它们
- C++将文本从.txt文件解析为变量
- 在树结构.txt文件中搜索节点
- 为什么我无法打开/读取从 Python 调用的 C 扩展名中的 txt 文件?
- 在 txt 文件中显示前两个数字的程序
- 如何从具有两列的.txt文件创建并行数组?
- 如何使用c ++读取带有非英文字母的*.txt文件?(国际化)
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 如何读取 TXT 文件并仅将 int 存储在 C 中