有如下data.txt
文件
// how to read .txt file.
2013001 2 6 8 14 15 24 25 6
2013002 3 1 16 18 22 28 30 12
2013003 1 22 23 26 27 28 33 9
2013004 4 6 10 16 20 27 32 8
2013005 3 1 13 14 25 31 32 12
2013006 1 9 10 13 17 22 30 13
2013007 4 2 9 15 22 26 32 1
2013008 4 3 8 17 21 25 32 15
2013009 2 1 4 9 13 16 23 2
2013010 2 1 9 11 17 32 33 12
2013011 4 3 12 17 24 27 29 9
2013012 4 6 14 17 22 28 29 2
2013013 2 5 6 13 19 22 28 9
c++ 使用fstream
流读取文件
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main(){
int row = 20, col = 9;
int arr[row][col] = {0}; // arr[a][b]在 (a, b) 位置
ifstream icin("data.txt");
string s;
getline(icin, s); // 读取第一行
//读取数据
int x;
int i = 0 , j = 0;
for(i = 0;i < 12;i++){
for(j = 0;j < 9;j++){
icin >> x;
arr[i][j] = x;
}
}
icin.close();
//输出读取的内容
cout << s << endl;
for(i = 0;i < 13;i++){
for(j = 0;j < 9;j++){
if(j == 0){
cout << arr[i][j] << " ";
}
else {
cout << std::left << setw(4) << arr[i][j];
}
}
cout << endl;
}
return 0;
}
输出结果
(全文完)