在C++中,可以使用fstream庫來讀取文件數(shù)據(jù)。以下是一個(gè)簡單的例子來演示如何讀取文件數(shù)據(jù):
#include <iostream>
#include <fstream>
int main() {
// 創(chuàng)建一個(gè)輸入文件流對象
std::ifstream file("example.txt");
// 檢查文件是否成功打開
if (!file.is_open()) {
std::cout << "無法打開文件" << std::endl;
return 1;
}
// 讀取文件數(shù)據(jù)
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
// 關(guān)閉文件流
file.close();
return 0;
}
在這個(gè)例子中,我們首先創(chuàng)建一個(gè)輸入文件流對象ifstream
,然后使用open
函數(shù)打開一個(gè)名為example.txt
的文件。然后我們使用getline
函數(shù)逐行讀取文件數(shù)據(jù),并將其輸出到控制臺(tái)上。最后我們關(guān)閉文件流。