Pelles C forum

C language => Beginner questions => Topic started by: sannemander on April 24, 2012, 05:16:40 PM

Title: problem getchar
Post by: sannemander on April 24, 2012, 05:16:40 PM
Hello, This code seems fine to me, the problem is when I enter a text and push enter nothing is happening, seems like getchar is not working at all.
What am I missing??

#include <stdio.h>

int main(void){

int NumberWords = 0, NumberLetters = 0;
float Average;
char ch;

    printf("Enter a sentence: ");

while ((ch = getchar()) != '\n'){
         NumberWords++;

while ((ch = getchar()) != ' '){
NumberLetters++;}
 
}


Average = NumberWords/NumberLetters;

printf(" Average word length: %1.f\n", Average);

return 0;
}
Title: Re: problem getchar
Post by: CommonTater on April 25, 2012, 12:46:02 AM
First problem is that you are calling getchar() twice on the same buffer without actually saving what is read in.  getchar() removes the character from the input buffer so your code never sees it.

Try rewriting your code to store the characters from your keyboard in a char buffer then make a second pass using a loop and array access on the resulting string to analyse the text after the user presses Enter. 




Title: Re: problem getchar
Post by: AlexN on April 25, 2012, 08:42:41 AM
Quote from: sannemander on April 24, 2012, 05:16:40 PM
Hello, This code seems fine to me, the problem is when I enter a text and push enter nothing is happening, seems like getchar is not working at all.
Why do you think getchar() is you problem.

If you try this code, the reseult will be near to that what you expect.
Average = 1.0*NumberLetters/NumberWords;       // if you calculate only with integer, the result will be an integer (even you store it in a float)

printf(" Average word length: %2.1f\n", Average); // if you store the result in a float, you perhaps what to see numbers behind the comma

And don't forget, getchar() starts reading you input after you pressed return.
Title: Re: problem getchar
Post by: sannemander on April 25, 2012, 10:18:40 AM
thx, solved the problem already:

#include <stdio.h>

int main(void){

int NumberWords = 1, NumberLetters = 0;
float Average;
char ch;

    printf("Enter a sentence: ");

while ((ch = getchar()) != '\n'){
         
        if (ch != ' '){
NumberLetters++;}

else if (ch == ' '){
      NumberWords++;}
}


Average = (float)NumberLetters/NumberWords;

printf(" Average word length: %.1f\n", Average);

return 0;
}