创建与输入名称相同的文件
creating the file with the same name as input
cout << "Enter your full name";
char* name ;
cin >> name;
if( _mkdir("c:\names") == 0 ) {
cout << "directory successfully created";
} else {
cout << "there was a problem creating a directory";
}
现在,我想在目录names
中创建一个文件(.txt文件(,其名称与user
的名称相同。我指的是用户在cin >> name;
期间输入的名称。
我该怎么做?
ofstream writeName( "c:/names/????);
---->问题
使用std::string
而不是char*
。事实上,您的代码具有未定义的行为。使用std::getline
而不是>>
。对于>>
,只输入第一个以空格分隔的"单词"。然后,在std::string
中组成完整的路径。标准字符串类支持串联,所以这应该很容易。
假设字符串是path
,
std::ofstream f( path.c_str() );
干杯&hth。,
您可以通过fopen
或ofstream
创建文本文件。
但是您为name
输入的方式似乎是错误的。您没有为name
分配空间。尝试使用malloc
或new
char*
指向一个字符。由于它没有初始化,它指向涅盘->未定义的bahavior。
您可以尝试使用char name[MAX_LENGTH_FOR_YOUR_NAME]
。这里最好使用std::string name
。
相关文章:
- C++文本文件输入
- C++ 中文件输入输出中的长长 v/s int
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 用空格填充 2D 数组(从文件输入)
- 流对象来表示文件输入,然后是标准输入?
- 用精神解析文件输入
- 从文件输入和输出
- 来自文本文件输入 c++ 的向量
- 如何通过键盘或分数文件输入分数
- 了解文件输入和输出,我可以写入文件,但无法从文件打印
- 词频程序 - 文件输入太大?
- 尝试从 csv 文件输入大量数据时出错
- 如何将文件从文件输入到C 中的矩阵中
- 如何从Windows CMD运行可执行文件并将其传递给文件输入的参数参数和重定向
- 如何解析文本文件并使用构造函数中的文件输入来创建对象的容器
- 这是读取文件输入的正确方法吗?
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- 如何创建一个具有空值、递减编号系统和.txt文件输入值的二维阵列网格
- C 文件输入流循环问题
- 使用对输入整数的文件输入