閱讀本文可首先參考:
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
有興趣的讀者可以將之改為一個函數,用到時直接調用即可,程序讀不懂的地方可以留言!