1. 程式人生 > >C++讀取txt檔案資料

C++讀取txt檔案資料

本次實驗主要目的是實現C++提取txt檔案的資料,txt檔案中的資料為double型。

txt檔案的資料為

1.123456789098 2.123456789098 3.123456789098 
4.123456789098 5.123456789098 6.123456789098
7.123456789097 8.123456789098 9.123456789098 

主要程式碼為:

  #include <iostream>
  #include <vector>        //提供向量標頭檔案
  #include <algorithm>     // 演算法標頭檔案,提供迭代器
  #include <fstream>       //提供檔案標頭檔案
  #include <iomanip>       //C++輸出精度控制需要
   
  using namespace std;
  int main()
  {
     vector<double> V;
     vector<double>::iterator it;
     ifstream data("t.txt");
     double d;
     while (data >> d)
         V.push_back(d);//將資料壓入堆疊。//
     data.close();
     int i = 0;
     for(it = V.begin();it != V.end();it++)
     {
         cout << "V[" << i << "]="<< setprecision(16) << *it << endl;
         i++;
     }
     return 0;
 }

輸出為: