C++指定路径创建txt文件并将从键盘获得的一串字符写进文件中
时间: 2024-10-17 17:05:34 浏览: 43
在C++中,你可以使用`fstream`库来指定路径并创建txt文件,然后通过`std::cin`从键盘获取输入内容并将其写入文件。下面是一个简单的示例:
```cpp
#include <iostream>
#include <fstream>
int main() {
// 指定文件路径和名称
std::string filePath = "path/to/your/file.txt";
try {
// 创建文件流对象
std::ofstream file(filePath);
if (!file) {
throw std::runtime_error("Failed to open the file for writing.");
}
// 提示用户输入一串字符
std::cout << "Please enter a string: ";
std::string input;
std::getline(std::cin, input);
// 将输入写入文件
file << input;
std::cout << "Characters entered have been written to the file.\n";
// 关闭文件流
file.close();
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
}
return 0;
}
```
在这个例子中,我们首先尝试打开一个名为"file.txt"的新文本文件,如果成功则提示用户输入字符,接着将输入的内容写入文件,最后关闭文件。
阅读全文
相关推荐


















