阅读量:135
在C++中,可以使用std::ifstream类来读取文件内容。下面是一个简单的示例代码:
#include
#include
int main() {
std::ifstream file("example.txt"); // 打开文件
if (file.is_open()) { // 检查文件是否成功打开
std::string line;
while (std::getline(file, line)) { // 逐行读取文件内容
std::cout << line class="hljs-comment">// 输出每一行内容
}
file.close(); // 关闭文件
} else {
std::cout << "无法打开文件" << std class="hljs-keyword">return 0;
}
在上述代码中,使用std::ifstream类打开文件,并使用std::getline()函数逐行读取文件内容。读取的每一行都被打印到标准输出中。最后,使用file.close()关闭文件。
请确保在运行代码之前,当前目录下存在一个名为example.txt的文件。