c++读取txt文件

有如下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;
}

输出结果

这里写图片描述

(全文完)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值