C

Scanf String in C

In this tutorial, we are going to see how to use scanf() string function in C.

You can use the scanf() function to read a string of characters.

The scanf() function reads the sequence of characters until it meets a space.
 

How to use Scanf in C

In the following program. Even if the name “Alex Douffet” was entered, only “Alex” was stored in the str array.

#include <stdio.h>

int main()
{
  char str[50];
  
  printf("Enter your name: ");
  scanf("%s", str);
  
  printf("Your name is %s.", str);
  return 0;
}

Output:

Enter your name: Alex Douffet
Your name is Alex.
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?

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 *