“How to input multiple characters in C language?”

In the C language, we can use the scanf function to input multiple characters. The scanf function is a formatted input function that reads data from the standard input stream based on a given format.

Below is a sample code demonstrating how to input multiple characters:

#include <stdio.h>

int main() {
    char str[100];  //用于存储输入的字符
    printf("请输入多个字符:");
    scanf("%s", str);  //使用%s格式化字符串来读取多个字符
    printf("您输入的字符是:%s\n", str);
    
    return 0;
}

In the code above, we start by declaring a character array named ‘str’ to store the input characters. Next, we use the printf function to prompt the user to enter multiple characters. Then, we use the scanf function with the %s format string to read the characters and store them in the ‘str’ array. Finally, we use the printf function to print out the characters that the user entered.

Be aware that when using the %s format string, the scanf function will automatically determine the end of input based on spaces or newlines. Therefore, if you want to input multiple characters separated by spaces, you can use the fgets function instead of the scanf function.

#include <stdio.h>

int main() {
    char str[100];  //用于存储输入的字符
    printf("请输入多个字符:");
    fgets(str, sizeof(str), stdin);  //使用fgets函数读取多个字符
    printf("您输入的字符是:%s\n", str);
    
    return 0;
}

In the code above, we use the fgets function instead of scanf to read multiple characters separated by spaces. The fgets function will continue reading characters until it encounters a newline character and will store the result in the str array. Please note that we also need to use the sizeof function to specify the maximum number of characters to read in order to prevent buffer overflow.

bannerAds