C

How To Read String With Spaces in C

In this tutorial, we are going to see how to read a string with spaces in C.

You can use the scanf() function to read a string of characters, but the scanf() function reads the sequence of characters until it meets a space. So if the string contains spaces, scanf() function doesn’t work. For example if you type “Alex Douffet”, only “Alex” will be stored in the str array. Instead you should use the fgets() function.
100-multiple-choice-questions-in-c-programming100 Multiple Choice Questions In C Programming – Part 1This collection of 100 Multiple Choice Questions and Answers (MCQs) In C Programming : Quizzes & Practice Tests with Answer focuses on “C Programming”.  …Read More

How To Read a String With Spaces in C

You can use the fgets() function to read a string with spaces. And, you can use the put() function to display the string.

#include <stdio.h>

int main()
{
  char str[50];
  
  printf("Enter your name: ");
  // read a string
  fgets(str, sizeof(str), stdin); 
  
  printf("Your name is: ");
  // display the string
  puts(str);  
  
  return 0;
}

Output:

Enter your name: Alex Douffet
Your name is: Alex Douffet

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *