Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

String scanf

  1. User

    String scanf

  2. Assistant

    scanf is 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 %s format specifier in scanf(). 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 %s in scanf reads a string input from standard input and stores it in the name array.

    Note that scanf does 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 %19s in the example above, which reads up to 19 characters into name. The last element of the array is used to store the null character in C, which indicates the end of the string.