0

print input one word per line

Hello everyone, I'm a little confused with the code below. It works fine, but I don't understand the concept of checking if "state" is either IN or OUT. for example, in the if statement, "if (c == ' ' || c == '\n' || c == '\t')" this checks if "c" is currently outside of a word, so if this is true, why would it be checking if "c" is == to IN ? IN is suppose to mean that it's inside of a word. Appreciate any help. thanks. #define IN 1 #define OUT 0 int 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); } } }

1st Jul 2021, 11:03 PM
David
David - avatar
4 Respuestas
+ 1
Although there are better approaches to solve this problem ( as already discussed by Martin Taylor ) But here is the reason as to why this program is checking "state":- Suppose the contents of file are "hello world" While reading characters 'h', the program haven't read any whitespace and the "state" is OUT ( control will go inside *else if* block ), so first the state of OUT would be flipped to IN and then 'h' would be printed to the stdout. For rest of the characters "ello", the control will go inside *else* block and characters would be printed as is. Now when the program reads the whitespace character between the two words ( the control will go inside *if* block now ), the "state" is flipped to OUT from IN ( suggesting that we have moved out of the word ) and a newline character is printed. Now the word "world" would again be read in similar manner. The reason for program to check *if(state == IN )* inside the first *if* statement is to make sure that the state is OUT when a whitespace is read.
2nd Jul 2021, 1:49 AM
Arsenic
Arsenic - avatar
+ 1
Arsenic thank you for helping me with this and breaking it down. I get it now.
2nd Jul 2021, 4:12 AM
David
David - avatar
0
Thank you Martin Taylor. Im going off of a book and its a little dated. Appreciate your help.
2nd Jul 2021, 12:14 AM
David
David - avatar
0
Thank you Martin Taylor. Always appreciate your answers.
19th Jul 2021, 8:03 PM
David
David - avatar