6/25/2008

Exercise1-8

Exercise1-8
Write a programto count blanks,tabs and newlines



1.1st try
----------------------------------------------------------
#include <stdio.h>
/*initialize the varibles*/
int c,b,t,n;

/*get start the counting*/
printf("Please enter a sentence for testing")
if ((c = getchar()) = ' ')
++b;
else if ((c = getchar()) = 't')
++t;
else if ((c = getchar()) = 'n')
++n;

printf("blank(s) ---> %d
tabs(s) ---> %d
newline(s) ---> %d",b,t,n);
----------------------------------------------------------
This time I've made a mistake.I don't use the 'while' loop,instead I use if wondering it may run a loop in program,but the complier says there's many errors in this program,I think it's something to do with the 'if'
So,now I should remember that:'If' can't run a loop!
While,let's go back to the loop itself,in order to get in into loop,we should use 'while',noting
while((c = getchar()) != EOF)
the key word 'EOF' make it possible to go over all the sentenc character as what the book teaches.
Hey!Poor guy!You forgot main() at the beginning of this program!!!!!!
What's more,the printf("") shouldn't be noted like this!

2. 2nd try
----------------------------------------------------------
#include <stdio.h>
/*initialize the varibles*/
main()
{
int c,b,t,n;

b = 0;
t = 0;
n = 0;

printf ("Please enter a sentence for testing");

/*start the counting*/
while ((c = getchar()) != EOF)
if (c = ' ')
++b;
else if (c = 't')
++t;
else if (c = 'n')
++n;

/*output the result*/
printf("blank(s) %dntabs(s) %dnnewline(s) %d", b,t,n);
}
----------------------------------------------------------
This time I've get this program run,but,It really don't run as what I expected,I hope to have this result that,after entering a sentence for test and then click on 'ctrl + c' and then an 'Enter',I expect it dispaly such words like:
blank(s) 3
tabs(s) 4
newline(s) 5
ect.
But the result is against it!It doesn't display anything,and it really makes me very anoying
Oh,my god,today's exercise is really terrible,but I will email kimiya for help,if he's free he might give me the answer before tomorrow.

No comments:

Post a Comment