There are several mistakes in the program
The array passed to scanf
is wrong.
fflush(stdin)
is non-standard, although Windows does support it it's not portable. But you aren't using Windows because it does not support the VLA char materia[V][50];
The newlines which the scanf
format "%[^\n]"
will stop at, are already the next character in the input buffer.
The return value from scanf
was not checked. It is the number of items successfully scanned.
You can have buffer overflow because the input string length is not restricted.
Here is the adjusted code:
#include<stdio.h>
int main(int argc, const char *argv[]){
int i;
int V;
printf("Enter number of Materi: ");
if(scanf("%d", &V) != 1) {
/* add some error message */
return 1;
}
// fflush(stdin); // removed
//Insert materia
char materia[V][50];
for(i = 0; i < V; i++){
printf("Materia %d name : ", i+1);
// add a space to filter the newline
// correct the array passed
// and restrict the length to prevent buffer overflow
if(scanf(" %49[^\n]", materia[i]) != 1) {
/* add some error message */
return 1;
}
// fflush(stdin); // removed
}
for(i = 0; i < V; i++){
printf("Materia - %d: %s\n", i+1, materia[i]);
}
return 0;
}
About the newlines. Format specs %d
and %s
and %f
automatically filter out leading whitespace, but %c
and %[]
and %n
do not. The scanf
functions stop at the first character they cannot convert, which is left in the input buffer. The %[^\n]
tell it to stop at the first newline. But there is one already there, from the first %d
scanf and it needs to be removed, also in subsequent iterations and adding the space does that job. Trying to remove it afterward is clumsy and not guranteed to work.
You must check the return value from scanf
every time it is used. It is the number of items successfully scanned. Here, it should be 1
in both uses. So if you have two items in one statement, its return value must be 2
.