C++读数字txt的一个小demo

inputs.txt 内容

5
45 12 45 6 8
27 36 12 4 56
34 0 12 4 58
69 24 1 45 9
3 81 5 27 8
#include <iostream>

int main(){

    FILE *fp;
    char file_path[1024]=".\\input.txt";
    int total_input;
    int cost_matrix[10][10]; // 存数据的数组

    // std::cout << sizeof(file_path) << std::endl; // 输出 1024
	
	rewind(fp);
    fp = fopen(file_path , "r");

	fscanf(fp, "%d", &total_input);  // 读取第一行的数字, 存入 total_input 中
	for(int i=0; i<total_input; i++){
		for(int j=0; j<total_input; j++)
			fscanf(fp, "%d", &cost_matrix[i][j]);
    }

    // 数据打印出来看看
    for(int i=0; i<total_input; i++){
		for(int j=0; j<total_input; j++)
			std::cout << cost_matrix[i][j] << "\t";
        std::cout << std::endl;
    }

    return 0;
}   

打印输出

45      12      45      6       8
27      36      12      4       56
34      0       12      4       58
69      24      1       45      9
3       81      5       27      8

简单说一下

  • rewind(fp) 函数,是将光标移动到文件开头

    fscanf 每读一些内容,光标就要往后移动一些位置,如果每读一些内容,执行一下rewind

    那么最后的数据 cost_matrix,将全部为 5

  • fscanf 函数写入多个变量内容的demo

    fp = fopen ("file.txt", "w+");
    fputs("We are in 2014", fp);
    
    rewind(fp);
    fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
    

    参考自:
    https://www.runoob.com/cprogramming/c-function-fscanf.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值