C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers

114 comments

10,705 users

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

0 votes
4,206 views
asked Jan 8, 2014 by keem Expert (13,240 points)

1 Answer

0 votes
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.

2. Continuous stream of characters cannot be

directly supplied using scanf function.

2. Continuous stream of characters can be directly supplied

using getchar function

3. 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;

}

3. 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;

}

4. 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.

4. 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.
answered Jan 8, 2014 by rajesh Guru (39,140 points)

Related questions

0 votes
1 answer 3,075 views
0 votes
1 answer 36 views
0 votes
1 answer 1,433 views
1,433 views asked Jan 8, 2014 by keem Expert (13,240 points)
0 votes
1 answer 1,364 views
1,364 views asked Jan 8, 2014 by keem Expert (13,240 points)
0 votes
1 answer 52 views
...