ANSI C - how to read from stdin word by word?

c

Solution

@cnicutar is pretty close, but you apparently only want to start reading at something other than white-space, and want to stop reading a single word when you get to whitespace, so for you scanset, you probably want something more like:

while(scanf(" %49[^ \t.\n]%*c", i)) {

In this, the initial space skips across any leading white space. The scan-set then reads until it gets to a space, tab, new-line or period. The %*c then reads (but throws away) the next character (normally the one that stopped the scan).

This can, however, throw away a character when/if you reach the end of the buffer, so you may want to use %c, and supply a character to read into instead. That will let you recover from a single word longer than the buffer you supplied.

Problem

Code: ``` #include <stdio.h> int main(void) { char i[50]; while(scanf("%s ", i)){ printf("You've written: %s \n", i); } printf("you have finished writing\n"); return 0; } ``` One problem is that the code doesn't do as it is expected to. If I typed in: ``` abc def ghi. ``` It would output: ``` You've written: abc You've written: def ``` How can I fix it? The goal is to read every single word from stdin until it reaches "ENTER" or a "." (dot).

Original source