News:

Download Pelles C here: http://www.smorgasbordet.com/pellesc/

Main Menu

problem getchar

Started by sannemander, April 24, 2012, 05:16:40 PM

Previous topic - Next topic

sannemander

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;
}

CommonTater

#1
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. 





AlexN

#2
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.
best regards
Alex ;)

sannemander

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;
}