gpt4 book ai didi

c - 将文本文件中的数字列表读入二维数组

转载 作者:行者123 更新时间:2023-11-30 16:53:10 27 4
gpt4 key购买 nike

我正在尝试将文本文件中的数字读取到数组中。文本文件“snumbers.txt”有 5 行,每行 10 个数字,均以空格分隔:

11 10 23 3 23 98 39 12 9 10
10 23 23 23 23 2 2 2 2 2
…etc…

我的代码:

#include <stdio.h>
int main()
{
FILE *myFile;
myFile = fopen("snumbers.txt", "r");

//read file into array
int numberArray[100][100];
int i;



}

如果我访问numberArray[1][1],我该如何做到这一点,它会给我数字“23”。

最佳答案

这里是将输入文件读入数组的完整代码。我创建了一个“转换器”来读取字符并将其转换为数字。假设数字之间只有一个空格。您可以按原样使用它或从中学习,以便您可以使用以下示例实现一些解决方案:

#include <stdio.h>
#include <string.h>

int main(void){
FILE *myFile; // file pointer to read the input file
int i, // helper var , use in the for loop
n, // helper var, use to read chars and create numbers
arr[100][100] , // the 'big' array
row=0, // rows in the array
col, // columns in the array
zero=(int)'0'; // helper when converting chars to integers
char line[512]; // long enough to pickup one line in the input/text file
myFile=fopen("snumbers.txt","r");
if (myFile){
// input file have to have to format of number follow by one not-digit char (like space or comma)
while(fgets(line,512,myFile)){
col = 0; // reset column counter for each row
n = 0; // will help in converting digits into decimal number
for(i=0;i<strlen(line);i++){
if(line[i]>='0' && line[i]<='9') n=10*n + (line[i]-zero);
else {
arr[row][col++]=n;
n=0;
}
}
row++;
}
fclose(myFile);

// we now have a row x col array of integers in the var: arr
printf("arr[1][1] = %d\n", arr[1][1]); // <-- 23
printf("arr[0][9] = %d\n", arr[0][9]); // <-- 10
printf("arr[1][5] = %d\n", arr[1][5]); // <-- 2

} else {
printf("Error: unable to open snumbers.txt\n");
return 1;
}
}

关于c - 将文本文件中的数字列表读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40967064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com