好的,下面是使用 C++ 写一个程序,该程序会让用户输入指定的路径,然后程序会在该路径下写入一个名为 hello.txt 的记事本的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// 获取用户输入的路径
string path;
cout << "请输入路径:";
cin >> path;
// 创建输出文件流,并打开文件
ofstream out(path + "\\hello.txt");
if (!out) {
// 如果打开文件失败,输出错误信息
cout << "打开文件失败!" << endl;
return 1;
}
// 向文件中写入内容
out << "Hello, world!" << endl;
// 关闭文件
out.close();
cout << "写入文件完成!" << endl;
return 0;
}
这段代码使用了 iostream
和 fstream
头文件,分别用于输入输出流和文件流。使用 ofstream
类型的输出文件流来打开文件,并使用 <<
运算符向文件中写入内容。最后,使用 close
函数关闭文件。