C++學習筆記之由文本文件讀取數據到vector模板建立的二維數組 並存儲為新的文本文件


閱讀本文可首先參考:

C++學習筆記之輸入、輸出和文件

測試數據:

 1 /*讀取txt文件到二維數組*/
 2 #include <iostream>
 3 #include <fstream>
 4 #include <vector>
 5 #include <string>
 6 
 7 using namespace std;  8 
 9 typedef vector< vector<int> > D2array; //二維數組
10 typedef vector<int> D1array;           //一維數組
11 
12 
13 int main() 14 { 15     int row = 10; 16     int col = 10; 17     ifstream input("E:\\c++\\C++ code\\item_basedCF\\datafordebug.txt");//打開輸入文件 
18     ofstream output("E:\\c++\\C++ code\\item_basedCF\\mytext.txt");     //打開要寫入的文件,如果該文件不存在,則自動新建 
19     D2array out(row, D1array (col, 0));                                 //聲明一個二維數組,將讀入的數據寫入該數組
20 
21     if (!input.is_open())     //如果文件打開失敗
22  { 23         cout << "File is not existing!" << endl; 24         exit(1); 25  } 26 
27     for (int i = 0; i < row; i++) 28  { 29         for (int j = 0; j < col; j++) 30  { 31             input >> out[i][j] ;          //從輸入流對象input讀取字符到out
32             cout << out[i][j] << " "; 33             output << out[i][j] << " ";   //將字符存入輸出流對象output,因為output流已經和mytext.txt關聯,所以會被寫入該文件
34  } 35         cout << endl;                     //換行,否則顯示在一行
36         output << endl;                   //換行,否則文本全存在在一行
37  } 38         
39 
40  input.close(); 41  output.close(); 42 
43      system("PAUSE"); 44      return 0; 45 }

運行結果:成功讀入out,並且轉存到mytext.txt

有興趣的讀者可以將之改為一個函數,用到時直接調用即可,程序讀不懂的地方可以留言!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM