使用 C++ ifstream 從文字檔案中讀取整數


以下是一個使用 C++ ifstream 從文字檔案中讀取整數的示例。

示例

#include <fstream>
#include<iostream>
using namespace std;
int main() {
   //initialie the array size
   int arr[30];
   ifstream is("a.txt");
   int cnt= 0;
   int x;
   // check that array is not already full
   while (cnt < arr[30] && is >> x)
   // and read integer from file
   arr[cnt++] = x;
   // print the integers stored in the array
   cout<<"The integers are:"<<"\n";
   for (int i = 0; i < cnt; i++) {
      cout << arr[i] <<' ';
   }
   //close the file
   is.close();
}

輸出

The integers are:
1 2 3 4 5 6 7

更新時間:2019 年 7 月 30 日

6K+ 次瀏覽

開啟您的 職業

完成課程並獲得認證

開始
廣告