ifstream
是 C++ 标准库中的一个类,用于从文件中读取数据。以下是一个简单的示例,展示了如何使用 ifstream
进行文件读取:
<fstream>
头文件,因为 ifstream
类定义在这个头文件中。#include <iostream>
#include <fstream>
#include <string>
ifstream
对象,并打开要读取的文件。例如,要打开名为 example.txt
的文件,你可以这样做:std::ifstream inputFile("example.txt");
ifstream
对象将处于 failbit
状态,你可以使用 fail()
成员函数检查这一点:if (!inputFile) {
std::cerr << "Failed to open file." << std::endl;
return 1;
}
>>
操作符从文件中读取数据。例如,要读取文件中的所有整数,你可以这样做:int number;
while (inputFile >> number) {
std::cout << number << std::endl;
}
>>
操作符替换为适当的类型即可。例如,要读取字符串,可以使用 getline()
函数:std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
inputFile.close();
将以上代码片段组合在一起,你将得到一个完整的示例,展示了如何使用 ifstream
从文件中读取整数和字符串:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inputFile("example.txt");
if (!inputFile) {
std::cerr << "Failed to open file." << std::endl;
return 1;
}
int number;
while (inputFile >> number) {
std::cout << number << std::endl;
}
inputFile.close();
return 0;
}
这个示例将从名为 example.txt
的文件中读取整数和字符串,并将它们输出到控制台。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:如何用ifstream读取文件内容