天天看點

學習筆記 c++ (二維vector操作示例+檔案操作)

檔案中存放如下所示的 3 * 4 的矩陣資料,需要讀取出來,然後使用vector來存儲。

1, 6, 2, 10.5
11, 15.2, 2, 21
3, 9, 1, 7.5
           
  • 示例代碼
#include <iostream>
#include <string>
#include <fstream>

using namespace std; 

int main(){

        fstream matrixFile{"../matrix.txt" , ios_base::in};

        string line;

        if(matrixFile.is_open()){
          //循環讀取每一行,直到文末

          //針對每一行操作的對象,用于字元串切割、轉化
          stringstream ss ;

          //用于接收每一個數字
          float number ;

          //整個矩陣資料
          vector <vector<float>> matrixVector;


          //存儲每一行的矩陣
          vector <float> rowVector;


          while(getline(matrixFile , line)){
              cout << "line = " << line << endl;


              //每次開始前都清空行vector的資料
              rowVector.clear();

              //每次包裝前,都清空内部資料
              ss.clear();

              //包裝line資料,以便一會進行切割,
              ss.str(line);


              //循環進行轉化。
              while(ss >> number){

                  //擷取下一個字元,如果是逗号或者空白 則忽略它,丢棄它。
                  //然後while循環繼續執行,擷取下一個數字
                  if(ss.peek() == ',' || ss.peek() == ' '){
                      ss.ignore();
                  }
                  //往行裡面追加資料
                  rowVector.push_back(number);
              }
              //每一行填充完畢之後,再存儲到大的vector中
              matrixVector.push_back(rowVector);

          }

          //關閉檔案
          matrixFile.close();


          //最後在這裡,周遊列印二維vector即可。

            for (int i = 0; i <matrixVector.size() ; ++i) {

                for (int j = 0; j <matrixVector[i].size() ; ++j) {
                    cout << matrixVector[i][j] << " ";
                }

                cout << endl;

            }
      }else{
          cout << "檔案打開失敗"<<endl;
      }
    return 0 ;
}
           

繼續閱讀