Hi all This is a program that prints the input one word per line .Just wanted to know what is the use of macro IN & OUT Code: #define IN 1 #define OUT 0 main() { int c, state; state = OUT; while ((c = getchar()) != EOF) { if (c == ' ' || c == '\n' || c == '\t') { if (state == IN) { putchar('\n'); state = OUT; } } else if (state == OUT) { state = IN; putchar(c); }else putchar(c); } }
using those two macros avoid some erronous situation like if you first type a large number of space or tab,it would print a large number of newline if you would not have used that IN and OUT macros, but maximum number of compiler does not include this error and the the program can be run efficiently without those.For example i have used two compilers one is turbo c++ 4.5 which ignores those spaces and C-Free compiler which shows erronous result without thos, without macro Code: #include<stdio.h> main() { int c; while ((c = getchar()) != EOF) { if (c == ' ' || c == '\n' || c == '\t') { putchar('\n'); } else putchar(c); } }
hye again Iam still not getting it Here is a new a program Please check the bold text & explain me Code: #define IN 1 #define OUT 0 main() { int c, state,nl,nw,nc; state = OUT; nl=nw=nc=0; while ((c = getchar()) != EOF) { nc++; if(c=='\n') ++nl; [B]if (c == ' ' || c == '\n' || c == '\t') state=OUT; else if (state == OUT) { state =IN; ++nw; }[/B] } printf(" line=%d word%d char=%,nl,nw,nc);
i am taking the old example, say you have entered "Hello go 4 expert forum" Now the State is set to OUT or 0 first, the first character encountered is H so it directly goes to else if statement (as the state=OUT initially) now the state is set to IN or 1 and prints the H. Next the 'e' is encountered but the state is set to 1 so it goes to last else statement (as all if fails) and prints the character. When the first ' ' blankspace is encountered the program enters the first if blocks there it is checked whether the state is IN or not (for reason keep reading) if the state is IN (as in the taken example) the program prints one newline character and set teh state to OUT, Now why this IN and OUT?? see if we would have taken an example like " Hello go 4 expert" i.e. with lots of space within it, then what would happen First it will encounter a blank space so the program enters the first block of if statement, but the state is set to OUT at first step ..... so the nested if statement fails within first if statement, first space is encountered and it's not printed on the screen ...... similarly it passes all the spaces and prints the first character i.e. 'H', if we would not use this IN & OUT then the output of the second input will be Hello go 4 expert Hello go 4 expert with IN and OUT it will print normally Hello go 4 expert (though in some new compiler you wont see any difference)