没有合适的资源?快使用搜索试试~ 我知道了~
在C++中,使用文件流(std::ifstream 和 std::ofstream)可以方便地读取和写入文本文件 下面是一些示例
需积分: 1 0 下载量 165 浏览量
2024-05-17
12:55:51
上传
评论
收藏 25KB DOCX 举报
温馨提示
试读
2页
在C++中,使用文件流(std::ifstream 和 std::ofstream)可以方便地读取和写入文本文件。下面是一些示例代码,展示了如何使用这些文件流来操作文本文件。 读取文本文件 cpp #include <iostream> #include <fstream> #include <string> int main() { std::ifstream inputFile("example.txt"); // 打开文件用于读取 if (!inputFile.is_open()) { // 检查文件是否成功打开 std::cerr << "Unable to open file"; return 1; } std::string line; while (std::getline(inputFile, line)) { // 逐行读取文件 std::cout << line << std::endl; // 输出读取到的行
资源推荐
资源详情
资源评论
在 C++中,使用文件流(std::ifstream 和 std::ofstream)可以方便地读取和写入
文本文件。下面是一些示例代码,展示了如何使用这些文件流来操作文本文件。
读取文本文件
cpp 复制代码
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inputFile("example.txt"); // 打开文件用于读取
if (!inputFile.is_open()) { // 检查文件是否成功打开
std::cerr << "Unable to open file";
return 1;
}
std::string line;
while (std::getline(inputFile, line)) { // 逐行读取文件
std::cout << line << std::endl; // 输出读取到的行
}
inputFile.close(); // 关闭文件
return 0;
}
在这个示例中,程序试图打开名为 "example.txt" 的文件以进行读取。如果文件成
功打开,它将逐行读取文件内容,并将每一行输出到控制台。
写入文本文件
cpp 复制代码
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream outputFile("output.txt"); // 打开文件用于写入
if (!outputFile.is_open()) { // 检查文件是否成功打开
std::cerr << "Unable to open file";
return 1;
}
outputFile << "Hello, World!" << std::endl; // 写入字符串到文
件
资源评论
梅菊林
- 粉丝: 1w+
- 资源: 207
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功