Can anyone explain how the below mentioned scanf
part will execute in while
loop for getting matrix input without boundary size in C?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char s[10000];
int a[100][100], rows = 0, cols = 0;
while (scanf("%[^\n]\n", s) == 1) {
char *num = strtok(s, " ");
int val = 0;
while (num != NULL) {
a[rows][val ] = atoi(num);
num = strtok(NULL, " ");
}
rows ;
cols = val;
}
for (int j = 0; j < cols; j ) {
for (int i = 0; i < rows; i )
printf("%d ", a[i][j]);
printf("\n)
}
}
CodePudding user response:
how the below mentioned scanf part will execute ...
scanf("%[^\n]\n",s)
weakly attempts to read a line of input.
Code then uses strtok()
to find tokens which are then parsed with atoi()
.
Code contains weaknesses.
Incorrect reading a a line of user input
"%[^\n]"
fails if the first character is '\n'
. Else it reads an unlimited number of non-'\n'
characters into s
, then appending a null character. "\n"
then reads in, and discards, 0 to an unlimited number of white-spaces including '\n'
, ' '
, etc.
while(scanf("%[^\n]\n",s)==1){
will stop the loop if the first line is only "\n"
, but will silently consume "\n"
otherwise. Lacking a width, it it worse than gets()
.
Perhaps scanf("