ProAnswers.org

What are the differences between getchar() and scanf() functions for reading strings in C?

Differences between getchar and scanf functions for reading strings:

scanf getchar

  1. Entering of each character should be followed

by return key. 1. Need not type return key.

  1. Continuous stream of characters cannot be

directly supplied using scanf function.

  1. Continuous stream of characters can be directly supplied

using getchar function

  1. Scanf function can be used to provide data at

execution time irrespective of its type(int, char,

float).

Example:

#include<stdio.h>

int main() {

char a[10];

printf("Enter a: \n");

scanf("%s",a);

return 0;

}
  1. getchar() function is used only with character type.

Example:

#include<stdio.h>

int main() {

char a;

printf("Enter any character: \n");

a = getchar();

printf("Character entered:%c \n",a);

return 0;

}
  1. scanf() returns the number of items read

successfully. A return value 0 indicates that no

fields were read. EOF(end of file) is returned in

case of an error or if end-of-file/end-of-string

character is encountered.

  1. getchar() returns the character entered as the value of the

function. It returns EOF in case of an error. It is recommeded

to use getchar instead of scanf.