Search code examples
carraysmultidimensional-arrayfgetsstrtok

Problems with fgets and strtok in C


I need to fill a 2d array with numbers from a string so I am using strtok and fgets to get the string and tokenize it. However if I enter "1 2 3 4 5" and the 2d array's dimensions are 2x2, the 5 never gets assigned to number. I want to check if there are more numbers than the matrix can hold but number always ends up being NULL after adding the 4 to the matrix instead of 5. I know SIZE is correct because if I print out stringInputted before strtok it prints out the correct output.

scanf("%d", &rows);
scanf("%d", &columns); 
//SIZE = 2*rows*columns+1
//rows and columns are user inputted and stored using scanf
fgets(stringInputted, SIZE, stdin);
 char *number = strtok(stringInputted, " \n");

 for(i = 0; i < rows; i++){
    for(j = 0; j < columns; j++){
        if(number != NULL)
            matrix[i][j] = atoi(number);
        else{
            printf("ERROR Insufficient numbers entered\n");
            return 0;
        }
        number = strtok(NULL, " \n");
    }
 }
 if(number != NULL) printf("TOO MANY NUMBERS\n");

Solution

  • Your SIZE is incorrect.

    fgets() reads in at most one less than size characters from stream... A terminating null byte ('\0') is stored after the last character in the buffer.

    So you need to consume 10 bytes, not nine.