6
\$\begingroup\$

I am working through the K&R and just finished exercise 1-12 and below is my solution. Exercise1-12: Write a program that prints input one word per line.

#include <stdio.h>


main()
{
    int c;

    while((c = getchar()) != EOF)
    {
        if(c == ' ' ||  c == '\t' || c == '\n')
        {
            putchar('\n');
            while(c == ' '|| c == '\t' || c == '\n')
             c = getchar();
        }
        putchar(c); 
    }
}

My question is both author and solutions here defined and used the state variable. when we compare my solution is pretty simple but it works. am I missing something? maybe there is a case that my solution won't work well?

Looking for your comments to improve, Thanks

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

To get a historically correct impression of programming in C, K&R is probably the best book available. In addition to that book, you should also get a more modern book about C since K&R doesn't teach you anything about function prototypes and buffer overflows (one of the main reasons that software written in C is often unreliable).

For example, the page you linked has a solution containing char buffer[1024];. That solution will fail with unpredictable behavior as soon as you pass it a file containing very long words, as the buffer will overflow and the C program will not reliably crash but is free to do anything it wants, including crashing or making daemons fly out of your nose. This is called undefined behavior.

There's not much to improve about your code. To make it modern, you simply have to replace one line:

main()              // before
int main(void)      // after

After that, you should tell your editor to format the source code. This will indent the innermost line c = getchar() a bit more, so that it is clearly inside the while loop.

// before:
while(c == ' '|| c == '\t' || c == '\n')
 c = getchar();

// after:
while (c == ' '|| c == '\t' || c == '\n')
    c = getchar();

Some other reviewers will say that you must always use braces in the if and while statements, but I disagree. It's enough to let your editor or IDE format the source code automatically, this will make it obvious when your code is indented wrongly.

\$\endgroup\$
2
  • \$\begingroup\$ What about ctype.h and isspace(int c)? \$\endgroup\$
    – pacmaninbw
    Commented Feb 16, 2020 at 17:57
  • \$\begingroup\$ Indeed, that would have been simpler. \$\endgroup\$ Commented Feb 16, 2020 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.