i need help writing a program that counts the characters entered into a program untill EOF is reached. I have to use the getchar function and my program should output the number of characters entered.


thanks

We like to help those that show some effort, especially when it appears to be an assignment.

Show us what you've tried. Tell us what it does and what you expected it to do and we can help you make the two match up better.

(I wouldn't be surprised to find an example program kicking around here somewhere...did you do a search before you started a topic?)

We like to help those that show some effort, especially when it appears to be an assignment.

Show us what you've tried. Tell us what it does and what you expected it to do and we can help you make the two match up better.

(I wouldn't be surprised to find an example program kicking around here somewhere...did you do a search before you started a topic?)

sorry i forgot to post my code

#include <stdio.h>

int main() {

int i ;
int c;

while ( ( i = getchar() ) != EOF )
c++ ;

printf( "%d characters\n" , c) ;

return 0;
}

does this seem ok? ... when i run it ./a.out i click enter
then i enter a word say "daniweb" and press enter and then hit ctrl+d and it says 8 characters

Edited 7 Years Ago by bbballin: n/a

That looks like it ought to work.

The program is counting the characters in the word say "daniweb" and also counting the enter as it is also a character before the EOF.

if you entered "daniweb" ctrl+d enter, it should count 7.

sorry i forgot to post my code

#include <stdio.h>

int main() {

int i ;
int c;

while ( ( i = getchar() ) != EOF )
c++ ;

printf( "%d characters\n" , c) ;

return 0;
}

does this seem ok? ... when i run it ./a.out i click enter
then i enter a word say "daniweb" and press enter and then hit ctrl+d and it says 8 characters

where is c initialized ?

Comments
Tada! The actual thread solver.
This article has been dead for over six months. Start a new discussion instead.