How can we use the getchar() function to read multi character strings?
Answers
{
char str[20];
int iii=0;
while(iii < 19)
str[iii++] = getchar();
str[iii] = '\0'; //cap it
puts(str); //see it
return 0;
}
Answer: Program is given below
Concept : getchar() function
Given : getchar() function to read multi character strings
To Find : How can we use the getchar() function to read multi character
strings?
Explanation:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(){
long n = 0;
while(getchar() != EOF)
n++;
printf("%ld\n" , n);
}
When entering "abcde"
Output : 6
Explanation of the code :
When getchar() is called, no input is available, so it waits.
When pressing 'a'. It is not the end of a line, so no input is sent to program, getchar() has nothing to read, so it still waits.
When b is pressed. It is not the end of a line, so no input is sent to program, getchar() has nothing to read, so it still waits.
When c is pressed, it is not the end of a line, so no input is sent to the program, getchar() has nothing to read, so it still waits.
When d is pressed. It's not the end of a line, so no input is sent to the program, getchar() has nothing to read, so it still waits.
When e is pressed. It's not the end of a line, so no input is sent to program, getchar() has nothing to read, so it still waits.
When enter is pressed. Now it is the end of a line, so the input "abcde\n" is sent to the program.
getchar() now has input to read, so it returns 'a', increments n, and loops back to wait for input. Now, getchar() has more input to read from the rest of the characters in the line, so it returns 'b', increments n, and loops back to wait for input. And does the same for the rest of the elements.
#SPJ3