C – Read Multiple String Values from Single Line using Scanf()

To read multiple string values from a single line entered by user in a specified format via standard input in C language, use scanf() function and pass the format and variables as arguments.

scanf() reads input from stdin(standard input), according to the given format and stores the data in the given arguments.

For example, the following code snippet can read a string with two words separated by space and store the words in separate variables.

char firstName[30];
char lastName[30];
scanf("%s %s", firstName, lastName);

Here, %s %s is the format to read two string values separated by space character.

Examples

In the following example, we read multiple string values from the input entered by the user in standard input using scanf() function.

main.c

#include <stdio.h>

int main() {
    char firstName[30];
    char lastName[30];
    printf("Enter your name : ");
    scanf("%s %s", firstName, lastName);
    printf("First Name : %s\n", firstName);
    printf("Last Name : %s\n", lastName);
    return 0;
}

Output

Enter your name : Arjun Singh
First Name : Arjun
Last Name : Singh
Program ended with exit code: 0
Enter your name : Priya Rakesh
First Name : Priya
Last Name : Rakesh
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

In this C Tutorial, we learned how to read multiple string values from a single line entered by user via standard input using scanf() function.