read from stdin in C language – Code Example

Total
0
Shares

In this article you will get the codes to read data from stdin in C language. We will show how you can use multiple methods like getline(), getc(), putc() and scanf() to read lines or characters.

Code Example –

1. Using getline()

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

int main(void)
{

  printf("Write some text:\n");
  char *completeLine = NILL;

  size_t len = 0;
  getline(&completeLine, &len, stdin);

  printf("Your text - %s.\n", completeLine);
  return 0;

}

Output –

Write some text:
Hello this is my text.
Your text - Hello this is my text.

2. Using getc()/putc()

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

int main( ) {

   char singleCharacterFromInput;
   int lengthOfCharacters;

   printf("How many characters you want to enter: \n");
   fscanf(stdin, "%d", &lengthOfCharacters);

   printf("\nEnter %d characters :\n", lengthOfCharacters);

   int i;
   for (i=0; i<=lengthOfCharacters; i++)
   {
     singleCharacterFromInput = getc(stdin);
     putc(singleCharacterFromInput, stdout);
   }  

   fprintf(stdout, "\n");

   return 0;

}

Output –

How many characters you want to enter:
117
Enter 117 characters: 
Before hurting an animal, remember the time when you cried your heart out. It feels the same. Feels exactly the same.

3. Using scanf()

#include <stdio.h>

int main( ) {

   char stringOfGivenLength[100];
   fprintf( "Enter your text within 100 chars : \n");

   fscanf(stdin, "%s", stringOfGivenLength);
   fprintf( stdout,"\nYour Text: %s \n", stringOfGivenLength);

   return 0;

}

Output –

Enter your text within 100 chars :
Vegetables are all around you, yet you enjoy crying eyes.
Your Text: Vegetables are all around you, yet you enjoy crying eyes.