Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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).

like image 683
Max Avatar asked Dec 27 '22 02:12

Max


2 Answers

@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.

like image 198
Jerry Coffin Avatar answered Jan 12 '23 00:01

Jerry Coffin


How about:

scanf("%49[ ^\n.]", str)

Or something like that.

like image 40
cnicutar Avatar answered Jan 12 '23 00:01

cnicutar