C 中 fgets 和 strtok 的问题

Problems with fgets and strtok in C

我需要用字符串中的数字填充二维数组,因此我使用 strtokfgets 来获取字符串并将其标记化。但是,如果我输入“1 2 3 4 5”并且二维数组的维度是 2x2,则 5 永远不会分配给 number。我想检查是否有比矩阵更多的数字,但是 number 总是在将 4 添加到矩阵而不是 5 之后最终成为 NULL。我知道 SIZE 是正确的,因为如果我打印出来stringInputtedstrtok 之前打印出正确的输出。

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");

您的 SIZE 不正确。

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

所以你需要消耗 10 个字节,而不是 9 个。