c++从文件中读取一行数据并保存在数组中

从txt文本中读取数据存入数组中

 1 #include <iostream>
 2 #include <fstream>
 3 #include <string>
 4 #include <vector>
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     ifstream infile;
10     infile.open("1.txt");
11     if(!infile) cout<<"error"<<endl;
12 
13     string str;
14     int t1;
15 /*  while(getline(infile,str))   //按行读取,遇到换行符结束
16     {   
17         infile.getline(str,10);
18         cout<<str<<endl;
19     }
20 */
21  /*//存入vector
22     cout<<"存入vector"<<endl;
23     vector<int> ve;
24     while(infile>>t1)             //按空格读取,遇到空白符结束
25     {
26         ve.push_back(t1);         
27     }
28 
29     for(int i=0;i<ve.size();i++) 
30         cout<<ve[i]<<" ";
31     cout<<endl;
32 */
33 
34 //存入数组
35     cout<<"存入数组"<<endl;
36     int a[3][4];
37     int*p=&a[0][0];
38     while(infile>>t1)             //遇到空白符结束
39     {
40         *p=t1;
41          p++;
42     }
43     infile.close();
44     for(int i=0;i<3;i++)
45     {   for(int j=0;j<4;j++)
46            cout<<a[i][j]<<"\t";
47          cout<<endl;
48     }
49     return 0;
50 }

 参考博文:https://www.cnblogs.com/helinsen/archive/2012/07/26/2609251.html

http://blog.csdn.net/u010220351/article/details/52347631

posted @ 2018-03-15 18:23  feifanren  阅读(14058)  评论(0编辑  收藏  举报