溫馨提示×

c++怎么從文件中讀取數(shù)據(jù)

c++
小億
226
2023-08-04 12:20:22
欄目: 編程語言

在C++中,可以使用fstream庫中的ifstream類來從文件中讀取數(shù)據(jù)。以下是一個簡單的例子:

#include <iostream>
#include <fstream>
int main() {
// 創(chuàng)建 ifstream 對象并打開文件
std::ifstream file("data.txt");
if (file.is_open()) { // 檢查文件是否成功打開
std::string line;
// 逐行讀取文件內(nèi)容
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close(); // 關(guān)閉文件
} else {
std::cout << "無法打開文件" << std::endl;
}
return 0;
}

上述代碼中,ifstream對象file被創(chuàng)建并用于打開名為data.txt的文件。使用getline函數(shù)逐行讀取文件內(nèi)容,并將每行打印到標(biāo)準(zhǔn)輸出。最后,使用close函數(shù)關(guān)閉文件。

請確保在讀取文件之前文件已經(jīng)存在,并且程序具有訪問該文件的權(quán)限。

1