Hello, I am a student who is learning programming in C language these days. One of the things you have to do is open the data.txt file and save it as an array and solve the problem using those arrays, but I don't know how to open the file and save it as an array. The data.txt file is now
-2, 3, 4
1, -3, -4
It's saved like this. To open it up
FILE *fp;
fp=fopen("data.txt", "r");
for (ch = getc(fp); ch != EOF; ch = getc(fp))
if (ch == '\n')
r = r + 1;
c = r + 1;
I think I opened the file like this and got the total number of rows and rows after that, but I don't know if this is right. After that, I'm going to save it in an array, but if I use malloc, I think I can get the value of each array, so I'm going to use it, how do I do it?
int **arr = (int **)malloc(r * sizeof(int *));
for (i = 0; i < r; i++) {
arr[i] = (int *)malloc(c * sizeof(int));
}
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
fscanf(fp, "%d", &arr[i][j]);
printf("%d\n",arr[i][j]);
}
}
I thought it would be saved if I did, but it doesn't Please help me
As the final goal, if you do printf("%d", mat[0][0])
, you can get -2.<
I wrote it assuming that the number of columns is 3
If the number of columns varies from line to line, we need to modify it a little bit
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COL 3
main(){
FILE *fp = fopen("data.txt", "rb")?: puts("fopen error");
char *buf, *iter = buf;
int (*mat)[COL] = malloc(BUFSIZ * COL * sizeof(int));
for(int cnt=0; (*iter = fgetc(fp)) != EOF; iter++){
if(strchr(",\n", *iter)){
mat[cnt / COL][cnt++ % COL]= atoi(buf);
buf = iter + 1;
}
}
printf("%d", mat[0][0]);
free(mat);
fclose(fp);
}
code execution button is because
It's probably because you can't create and access the data.txt file We'll do well with the local C compiler
© 2024 OneMinuteCode. All rights reserved.