阅读本文可首先参考:
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
有兴趣的读者可以将之改为一个函数,用到时直接调用即可,程序读不懂的地方可以留言!