Input is
"C\n"
, "Language\n"
, "Welcome To C!!\n"
.
scanf("%c", &ch);
reads "C"
. "\nLanguage\nWelcome To C!!\n"
remains. "%c"
reads/saves 1 character.
scanf("%s", s);
reads "\nLanguage"
. "\nWelcome To C!!\n"
remains. "%s"
reads/discards leading white-space and reads/saves unlimited non-white-space characters, then appends a null character to s
.
scanf("%[^\n]%*c", sen);
reads nothing. "\nWelcome To C!!\n"
remains. "%[^\n]%*c"
stops immediately because the first available character is a '\n'
and that is not in the scanset [^\n]
. sen
unchanged.
what is the problem with last printf
printf("%s\n", sen);
attempts to print from the unassigned sen
array leading to undefined behavior (UB).
what could be the wrong here?
Failure to check the return value of scanf()
in 3 places
With if (scanf("%[^\n]%*c", sen) != 1) puts("Error");
, It would become clear, nothing was read.
Using "%s"
and "%[^\n]"
without a width
scanf("%s", s);
risks input overflow. Use a width like scanf("%99s", s);
with char s[100];
Could also change code to consume leading white-space.
// scanf("%[^\n]%*c", sen);
// v---- Note space.
if (scanf(" %99[^\n]%*c", sen) != 1) {
puts("Error");
}
Even better, stop using scanf()
and use fgets()
for all user input. Read into a string and then parse.