Here we are taking baby steps in c. Lets learn how to count the number of characters entered through stdin (standard input like keyboard).
We will try to code the program similar to my earlier posts.
Though we can code above snippet in much simpler form, I have used my earlier programs code to count the number of characters in c.
From above program,
We will try to code the program similar to my earlier posts.
#include <stdio.h>
int main()
{
int c,count=0;
printf("Start your input \n");
c = getchar();
while(c != '\n')
{
putchar(c);
c = getchar();
++count;
}
printf("\n Number of characters entered = %d\n",count);
}
Though we can code above snippet in much simpler form, I have used my earlier programs code to count the number of characters in c.
From above program,
- In a while loop, we take input from stdin
- output the characater to stdin
- read character
- pre-increment the count value
- Continue in the while loop till new line
- When new line is encountered, we print the stdout and number of characters
Output of this program is below
mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out
Enter Ctrl+C is to exit
Start your input
just a single line input
just a single line input
Number of characters entered = 24
Note that we are printing the characters and number of characters when new line or carriage return is encountered.
No comments:
Post a Comment