NO

Author Topic: problem getchar  (Read 2894 times)

sannemander

  • Guest
problem getchar
« 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??

Code: [Select]
#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

  • Guest
Re: problem getchar
« Reply #1 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. 




« Last Edit: April 25, 2012, 12:48:13 AM by CommonTater »

Offline AlexN

  • Global Moderator
  • Member
  • *****
  • Posts: 394
    • Alex's Link Sammlung
Re: problem getchar
« Reply #2 on: April 25, 2012, 08:42:41 AM »
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.
Code: [Select]
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.
« Last Edit: April 25, 2012, 08:44:50 AM by AlexN »
best regards
 Alex ;)

sannemander

  • Guest
Re: problem getchar
« Reply #3 on: April 25, 2012, 10:18:40 AM »
thx, solved the problem already:

Code: [Select]
#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;
}