0

In the following code, I am trying to read a CSV file (in the order: #,#,#,#) into a 2D array. However, I am running into a problem where this line

arry[counter][0] = atoi(numOne);

is not working. In specific, atoi(numOne) is returning 0. However, it prints its int value fine in printf("%s", numOne);

As a result, my array looks like this:

0,1,3,2

0,0,5,4

0,9,8,1

0,10,6,3

With the first item of each row missing.

Why is this?

FILE *fp = fopen(argv[1], "r");
int counter = 0;
char line[150];
while (fgets(line, 150, fp)) {
    printf("%s", line);
    counter++;
}
int arry[counter-1][4];
NUM_ROWS = counter - 1;


rewind(fp);
//Skip First Line of Var Names
fgets(line, 150, fp);
counter = 0;

while(fgets(line, 150, fp)) {
    char *numOne = strtok(line, ",");
    char *numTwo = strtok(NULL, ",");
    char *numThree = strtok(NULL, ",");
    char *numFour = strtok(NULL, ",");


    arry[counter][0] = atoi(numOne);
    arry[counter][1] = atoi(numTwo);
    arry[counter][2] = atoi(numThree);
    arry[counter][3] = atoi(numFour);

    printf("%s%s%s%s", numOne, numTwo, numThree, numFour);

    counter++;
}
wirly
  • 27
  • 6
  • "However, it prints its int value fine in printf("%s", numOne);" *How do you know*? Your code doesn't have such a statement. You are instead printing each value together, *with no delimiter* - how can you be sure how much of the output comes from `numOne` etc.? – Karl Knechtel Jun 15 '21 at 03:21
  • @KarlKnechtel Hi Karl, I know because numOne in this statement printf("%s%s%s%s", numOne, numTwo, numThree, numFour), the first space (where numOne is placing) is running the correct number from the CSV file. I have run printf("%s", numOne) and received the same number. (Logically placed in CSV file there as well) – wirly Jun 15 '21 at 03:32
  • As I commented under [the duplicate](https://stackoverflow.com/questions/67978690), you should [edit] the question, and post the first three lines of the file so we can see what's actually in the file. – user3386109 Jun 15 '21 at 03:50
  • What do you mean "the first space"? If you see `1234`, how do you know that it isn't an empty string, and then `"12"`, `"3"` and `"4"`? – Karl Knechtel Jun 15 '21 at 04:11
  • [Why shouldn't I use atoi()?](https://stackoverflow.com/q/17710018/995714) – phuclv Jun 15 '21 at 06:55

0 Answers0