C Program to read and write character string and sentence


Suppose you want to take a character, then a string and a sentence (string with spaces) using C. So we shall provide three inputs and print the same as output. The maximum size of the string is 500 here.

So, if the input is like

character = 'T'
string = "ProgrammingLanguage"
sentence = "I love programming through C",

then the output will be

Your character: T
Your string: ProgrammingLanguage
Your sentence: I love programming through C

To solve this, we will follow these steps −

  • For character we need to use scanf("%c", &character);

  • For string we need to use scanf("%s", string);

  • This step is optional, but required in some cases. Sometimes you may face one problem. Your program sometimes does not wait for next input, so we need to clear the buffer using fflush(stdin)

  • And for string with spaces we need to use fgets() function. Here the first parameter is string, second is the size and last one is stdin to take input from console.

  • The last one indicates we need one new line character to denote end of string. Otherwise it will take spaces as well.

Example

Let us see the following implementation to get better understanding −

#include <stdio.h>
int main(){
    char character;
    char string[500];
    char sentence[500];
    scanf("%c", &character);
    scanf("%s", string);
    fflush(stdin);
    fgets(sentence, 500, stdin);
    printf("Your character: %c
", character);     printf("Your string: %s
", string);     printf("Your sentence: %s
", sentence); }

Input

T
ProgrammingLanguage
I love programming through C

Output

Your character: T
Your string: ProgrammingLanguage
Your sentence: I love programming through C

Updated on: 08-Oct-2021

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements