c++读取文件内容并保存到二维数组
每行数据最后需要Tab处理
1 #include <iostream> 2 #include <fstream> 3 #include <string> 4 using namespace std; 5 6 int spilt_n(string s)//每行以‘\t’来统计有多个子字符串 7 { 8 const char *ch; 9 int i,count = 1; 10 ch = s.c_str(); 11 for(i=0;i<s.length()-1;i++) 12 { 13 if(ch[i]=='\t')count++; 14 } 15 // cout<<"count:"<<count<<endl; 16 return count; 17 } 18 19 int main() 20 { 21 ifstream in; 22 ofstream out; 23 24 in.open("D://test.txt",ios::in); 25 if(!in) 26 { 27 cout<<"open file fail!"; 28 }else cout<<"open file success!"<<endl; 29 30 31 string str[1000][20];//存放数据 32 string temp; 33 getline(in,temp,'\n'); 34 int num; 35 num = spilt_n(temp); 36 in.close(); 37 in.open("D://test.txt",ios::in); 38 // cout<<"num:"<<num<<endl; 39 int mid = 0; 40 int count =0; 41 while(!in.eof()) 42 { 43 // mid = 0; 44 if(mid<num) 45 { 46 getline(in,str[count][mid++],'\t'); 47 // cout<<"count"<<count<<",mid"<<mid<<":"<<str[count][mid++]<<endl; 48 }else{ 49 mid = 0; 50 count++; 51 } 52 } 53 54 // cout<<str[0]<<endl; 55 int i,j; 56 for(i=0;i<count;i++) 57 { 58 for(j=0;j<num;j++) 59 { 60 cout<<str[i][j]<<"\t"; 61 } 62 cout<<endl; 63 } 64 65 66 67 in.close(); 68 return 0; 69 }