Read a file and put in a array[][]

Hi guys,
I need to do a program that reads a file, that contains something like this:

8 2 3 4 2
5 6 1 3 4
3 1 4 6 7
7 2 4 1 3
3 2 1 6 8

and put in a array[][] in the program

I did this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
int main(){
    using namespace std;
    int size=0;
    char line[1300]; 
    FILE *file;
    char path[50];
    int l=0,c=0;

    printf("Path:");
    gets(path);

    file = fopen(path,"r");
    if(file == NULL) {
        printf("file unknown - nome_do_arquivo.txt\n");
        return 0;
    }
    while(fgets(line, sizeof(line), file) != NULL) {
        size++;
    }

    fclose(file);

    long double A[size][size];

    file = fopen(path,"r");

    if(file == NULL) {
        printf("file unknown - nome_do_arquivo.txt\n");
        return 0;
    }

    c=0;
    while(fgets(line, sizeof(line), file) != NULL) {
        for (int k=0; k<strlen(line);k++){
            if (line[k] != ' ') {
                printf("\nValue->%c", line[k]);
                printf("\nl=%d", l);
                printf("\nc=%d", c);
                A[l][c] = (float)line[k];
                c++;
            }
        }

        c=0;
        l++;
    }

    fclose(file);

    c=0;
    l=0;

    printf("\n\ntest->%.0f", A[3][3]);
    printf("\ntest->%d", size);

    return 0;
}


But when i print A[3][3], it does not contain the correct value, but I strange value, like -36893488147419103000
My idea was to pass line by line of the file, including the values that were not " ", to get only the numbers.
Somebody knows what might be happening?
Initialise the array like so:
long double A[size][size] = {0};

If you run the code again and you get a zero in the output, then the problem is with your code not the array.
Your conversion is bad in line 39. line[k] is not numeric type. Use atoi, atof, or strtod.
Test with this:
1
2
3
4
5
6
7
8
9
#include <stdio.h>

int main()
{
  char line[10]="3";
  long double a=(float)line[0];
  printf("\n\ntest->%.0f",a);
  return 0;
}


Quick notes on your program: you can obviously read only single digits. Why not read all the numbers into an array? The number of elements is going to be temp[n*n]. Then you can create the A[n][n] array. This has the advantage that you read the file only once
Topic archived. No new replies allowed.