I am trying to input a string in C and print it. My sample code is given below:
#include<stdio.h>
main()
{
char a[5];
scanf("%[^\n]a",a);
printf("%s",a);
}
The problem is, I have initially assumed the string length as 5. But if I take a string with length more than 5, it works correctly. Why is this happening? Shouldn't the permitted string length be less than 5?
scanf()(implicitly) the address ofa's 1st element. You need to explicitly tell it how much it may scan.ascans a float. To scan a "string" uses. If you have defined achar[5]that allows a possible "string" of length 5-1=4. C needs 1charto store "string's"0-terminator. To tellscanf()to only scan 4chars use%4s.%ainscanf?main()- implicitinthas been an error since C99.