C program to ask for a string from the keyboard and print it

You can read strings from the keyboard using several methods in c programming. Each method has some advantages and disadvantages. For example, you can tell your computer memory to store strings in a reserved memory using the scanf() function. As well as you can also read input with the gets() and fgets() function.

The variations of those three methods are, the function scanf() reads the first word of a given space separated sentence. On the other hand, if you use gets to read a string, then the function will read space-separated words also. fgets() also works almost the same as gets(), but the only differences is, fgets() takes a newline character automatically after every string you input.

Sample Input/Output

Sample Input Sample Output
Programming world! Programming world!

Logic to input a string

First of all write down the basic skeleton of  C source code with the standard input-output library definition, main function definition, and prepare for taking string input from the keyboard. Now;

  • Declare a character type array str with size 100 something like this char str[100] which is called especially string data type in C. This data type will store your said string.
  • Now after printing the input message to the user using printf() function, write the fgets() function for taking input from the keyboard.
  • The fgets() function consists of the following syntax, fgets(string_name, sizeof string_name, stdin). In the following case, string_name is str we used. And here, stdin means the standard input-output format.
    Thas all.
  • Finally, print the string using the simple printf() function.

C program to ask a string input and print it

#include <stdio.h>
#include <stdlib.h>
int main() {
    char str[100]; //maximum character to be hold

    /* Read multi-line string */
    printf("Enter desired string: ");
    fgets(str, sizeof str, stdin);

    /* Or use the following two syntax by swaping comment */
    // gets(str);
    // scanf("%s", str);

    printf("You entered: %s\n", str);

    return 0;

Happy coding! ^_^

Posted in