w3resource

C Programming: Accept a string from keyboard


1. String Input Print

Write a program in C to input a string and print it.

C Programming: Accept a string from keyboard


Sample Solution:

C Code:

#include <stdio.h>
#include <stdlib.h>

// Main function
int main() {
    char str[50]; // Declaring a character array to store the input string
	
    printf("\n\nAccept a string from keyboard :\n"); // Prompt to accept a string from the keyboard
    printf("-----------------------------------\n"); 	
    printf("Input the string : ");

    // Read a string from the standard input (keyboard) using fgets()
    fgets(str, sizeof str, stdin);

    // Display the string entered by the user
    printf("The string you entered is : %s\n", str);
	
	return 0; // Return 0 to indicate successful execution of the program
}


Output:

Accept a string from keyboard :                                                                               
-----------------------------------                                                                           
Input the string : Welcome, w3resource                                                                        
The string you entered is : Welcome, w3resource  

Flowchart:

Flowchart: nAccept a string from keyboard.


For more Practice: Solve these Related Problems:

  • Write a C program to input a multi-word string using fgets() and display it without trailing newline characters.
  • Write a C program to input a string using dynamic memory allocation and print it safely after validating the buffer size.
  • Write a C program to read a string containing spaces and special characters and then echo it exactly as entered.
  • Write a C program to input a string and display each character's ASCII value along with the character.

Go to:


PREV : C String Exercises Home
NEXT : String Length Without Library.

C Programming Code Editor:



Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.