How to input a string in C language?

In C language, you can use the scanf or gets function to input strings from the user.

  1. To take in input
#include <stdio.h>

int main() {
    char str[100];

    printf("请输入一个字符串:");
    scanf("%s", str);

    printf("输入的字符串为:%s\n", str);

    return 0;
}

The mentioned code firstly defines a character array str to store the input string. Then, it uses the scanf function to input the string in %s format and store it in str. Finally, it uses the printf function to print the input string.

  1. receives
#include <stdio.h>

int main() {
    char str[100];

    printf("请输入一个字符串:");
    gets(str);

    printf("输入的字符串为:%s\n", str);

    return 0;
}

The above code uses the gets function to input a string, stores the user input string in ‘str’, and then prints the input string using the printf function.

It is important to note that the gets function has security issues, so it is not recommended to use it. Instead, you can use the safer fgets function as a replacement for gets.

#include <stdio.h>

int main() {
    char str[100];

    printf("请输入一个字符串:");
    fgets(str, sizeof(str), stdin);

    printf("输入的字符串为:%s\n", str);

    return 0;
}

In the above code, the fgets function is used to input a string, store the user’s input in the variable str, and then print the input string using the printf function. Compared to the gets function, fgets has two additional parameters: the first parameter is the array where the input string will be stored, the second parameter is the size of the array, and the third parameter is the input stream. Typically, stdin can be used to represent the standard input stream.

bannerAds