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
函数写入多个变量内容的demofp = 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