Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

some questions about this 1

Status
Not open for further replies.

chopstick

Programmer
Apr 9, 2006
8
SG
the code is like this:
Code:
#include<stdio.h>
int main(void)
{
    
    float average;
    int flag=0;
    int c=0;
    int word=0;
    char ch;
    
  printf("pls enter your sentence:");
  while ((ch=getchar())!=EOF)
  {
        if(ch!=' '&&ch!='\n')
        c++;
        if(ch!=' '&&ch!='\n'&&flag==0)
        {
                     word++;
                    flag=1;
                    }
        if((ch=='\n'||ch==' ')&&flag==1)
        flag=0;
        }
        average=c/word; 
        printf("word are %d\n",word);
        printf("characters are %d",c);
        printf("the average is %f",average);
                                
                              
system("pause");
return 0;
}
I entered "this is a test" then followed by control+z, after hitting enter it does not give me anything, only the cursor moved to the next line. anything wrong?

If there is 11 characters and 4 words, it should give me an average of 2.75, but what I got was 2.00000...what went wrong?
thanks for help!
 
2nd question - either c or word has to be a float.

1st question - getchar returns an int. If you get the result as an int, it might work. This is very OS dependent.
 
> I entered "this is a test" then followed by control+z
Some terminal drivers on recognize the "EOF" at the start of a line.

So "this is a test"
Then enter
Then ctrl-z


--
 
What OS is this? The EOF character in Unix is Ctrl-D, not Ctrl-Z. Ctrl-Z is MS-DOS/Windows.
 
I don't believe UNIX has a "pause" command, so I'm guessing it's Windows.
 
just like Salem said, it only recognise control-Z at the beginning of a line, why?
 
> it only recognise control-Z at the beginning of a line, why?
Perhaps to allow you to type in a ctrl-z at other times, and have the program read character-26 like any other normal character.

There isn't an actual EOF key on the keyboard, so it has to be faked using what is available, and that necessarily entails some compromises in what you can do.

FYI, one one particular compiler, pressing ctrl-z twice at the end of a non-empty line also sends one EOF signal up from the terminal driver (YMMV).


--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top