Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

อ่านจำนวนเต็มจากไฟล์ข้อความด้วย C++ ifstream

ตัวอย่างการอ่านจำนวนเต็มจากไฟล์ข้อความด้วย C++ ifstream

ตัวอย่างโค้ด

#include <fstream>
#include <iostream>
using namespace std;

int main() {
    // กำหนดขนาดอาร์เรย์
    int arr[30];
    ifstream is("a.txt");
    int cnt = 0;
    int x;
    // ตรวจสอบว่าอาร์เรย์ยังไม่เต็ม และอ่านจำนวนเต็มจากไฟล์
    while (cnt < 30 && is >> x)
        arr[cnt++] = x;
    // พิมพ์จำนวนเต็มที่เก็บในอาร์เรย์
    cout << "The integers are:" << "\n";
    for (int i = 0; i < cnt; i++) {
        cout << arr[i] << ' ';
    }
    // ปิดไฟล์
    is.close();
    return 0;
}

ผลลัพธ์

The integers are: 1 2 3 4 5 6 7