ANSI C - how to read stdin word by word?

The 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 does not work as expected. If I typed:

abc def ghi.

It outputs:

You've written: abc
You've written: def

How can i fix this? The goal is to read every word from stdin until it reaches "ENTER" or "." (Dot).

+3
source share
4 answers

@cnicutar is pretty close, but you probably only want to start reading something other than white, and you want to stop reading one word when you fall into a space, so for you, scanning, you probably want something more

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

. , , , . % * c ( ) ( , ).

, , , / , % c , . , .

+5

:

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

- .

+4

scanf fgets:

while (fgets(i, sizeof i, stdin))
{
  printf("you've written: %s\n", i);
}

:

  • , fgets ;

  • ., , , :


    int foundDot = 0;
    while (fgets(i, sizeof i, stdin) && !foundDot)
    { 
      char *dot = strchr(i, '.');
      char *newline = strchr(i, '\n');

      if (dot != NULL)
      {
        foundDot = 1;
        *dot = 0; // overwrite the '.' character with the 0 terminator
      }

      if (newline != NULL)
      {
        *newline = 0; // overwrite newline character with 0 terminator
      }

      /**
       * Assuming you don't want to print a blank line if you find a dot
       * all by itself. 
       */
      if (strlen(i) > 0) 
        printf("you've written: %s\n", i);
    }
+2

The easiest way to do this is flex . Otherwise, you are repeating difficult, complicated work and you are probably mistaken.

Also read lex and yacc, 2nd edition .

-1
source

All Articles