String scanf
- User
String scanf
- Assistant
scanfis a function in the C programming language for inputting formatted data from standard input or a file. It belongs to the standard input/output library (stdio.h).A string input can be taken using the
%sformat specifier inscanf(). Here is an example:#include <stdio.h> int main() { char name[20]; printf("Enter your name: "); scanf("%s", name); printf("Hello, %s!\n", name); return 0; }Here,
char name[20]defines an array of characters with a maximum length of 20. The%sinscanfreads a string input from standard input and stores it in thenamearray.Note that
scanfdoes not check for buffer overflow, so it is important to ensure that the size of the buffer is sufficient for the input string. To avoid buffer overflow, it is possible to use the width specifier to limit the number of characters read, like%19sin the example above, which reads up to 19 characters intoname. The last element of the array is used to store the null character in C, which indicates the end of the string.