根据用户输入的字符串命名输出文件
Naming an output file from a user entered string
这是我在C++的第一个项目。我以前参加了一门使用 C 的课程,文件 I/O 似乎略有不同。
该项目要求用户输入用于保存输出文件的名称。
我知道我应该使用 ofstream,它应该看起来像这样:
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.n";
myfile.close();
我已经将引起混乱的片段加粗了。
如何从用户输入的字符串中命名文件?
*注意,C类型字符串,所以是一个字符数组。
不允许 #include <字符串>字符串>
由于我的另一个答案得到了反对票,这是另一种解决方案,没有#include <string>
您可以将用户的输入保存在临时 char 数组中,然后将其保存到字符串变量 std::string
中。
包括必要的:
#include <iostream>
#include <fstream>
将用户的输入保存到 char 数组中:
char input[260];
cin >> input;
然后将其保存在字符串变量中,只需执行以下操作:
string filename = input;
要打开文件流,您需要使用 std::ofstream
.请记住,该文件是在与项目/应用程序相同的文件夹中创建的。
std::ofstream outfile (filename + "." + "file extension");
如您所知,此outfile.open();
会打开文件。
使用outfile << "hello";
您可以写入文件。
若要关闭文件,请使用outfile.close();
关闭文件。
这里有一个小示例代码:
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
char input[260];
cin >> input;
string filename = input;
ofstream outfile(filename + "." + "txt");
outfile << "hello";
outfile.close();
}
我希望这有所帮助。
问候。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string path;
string name;
string h_path;
string text;
void create() {
ofstream file(h_path, ios::app);
if (!file.fail()) {
file << text;
file.close();
}
}
int main() {
cout << "please enter path(c:\folder): ";
cin >> path;
cin.ignore();
path = path + "/";
cout << "please enter the name of the file (test.txt): ";
getline(cin, name);
cout << "content of the file: ";
getline(cin, text);
h_path = path + name;
create();
cout << "new file created";
cout << h_path;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string fileName;
cin >> fileName;
ofstream myfile;
myfile.open(fileName);
myfile << "Writing this to a file.n";
myfile.close();
}
相关文章:
- 有没有办法简单地从 GPU 调用多个 cpp 输出文件?
- VI工作室代码错误无法打开输出文件主.exe
- 在代码块中查找输出文件
- 将未签名的字符写入输出文件
- 为什么我的代码不写入输出文件?
- 完成搜索任务时为空输出文件
- 如何将地图<列表<string>、矢量<string>>输出到输出文件?
- 无法在代码块 IDE 中打开输出文件.exe
- C++:更改 IF 语句中的输出文件
- 编译 gsoap 输出文件 (onvif) 时出现问题
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- while 循环中的流输出文件() 通常生成空文件
- 如何使用 Docker 访问输出文件
- 提升进程间共享内存删除、权限和输出文件
- 查找素数,然后将质数放入输出文件中
- GDB / C++ - 根据循环条件将多个变量记录到输出文件中
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 我的输出文件未显示解决方案
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- C++,我正在尝试创建一个有效的.bmp输出文件