如何在 C++ 中从文件中读取数据
在 C++ 中,从文件中读取数据的常用方法有两种:
1. 使用文件流
文件流是 C++ 中处理文件的一种方式,它提供了一组函数来读写文件。要使用文件流读取文件,需要执行以下步骤:
- 打开文件:使用
ifstream
类打开一个文件。 - 读入数据:使用
operator>>
或getline
等函数从文件中读入数据。 - 关闭文件:使用
close
函数关闭文件。
示例代码:
<code class="cpp">#include <fstream> #include <iostream> int main() { std::ifstream file("data.txt"); if (file.is_open()) { std::string line; while (std::getline(file, line)) { std::cout </iostream></fstream>