3

I want the following to ask for input and then take in a string (with spaces), then do it again. But it repeatedly outputs "input$" after typing in the first string.

char command[80];

while(1)
    {
        printf("input$ ");
        scanf("%[^\n]", command);    
    }

My output: nput$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$ input$^C

What I want:

input$ hi
input$ this can take spaces
input$
Lucas
  • 1,577
  • 6
  • 18
  • 25
  • You're better off just avoiding `scanf`. http://c-faq.com/stdio/scanfprobs.html – jamesdlin Feb 16 '12 at 06:08
  • 1
    The trouble is that once you've read to the first newline, the next character is a newline, so the `scanf()` reports that it was not able to convert anything (return value 0, not EOF), but you're blithely ignoring it. You have to read the newline (`getchar()`, perhaps) to allow it to continue. Or add a `\n` after the `]`; or, indeed, a space would do. If you don't care about leading spaces, a space before the `%` would work, too. It is incredibly hard to use the `scanf()` functions correctly; it is really 'cruel and unusual punishment' to make beginners use them. – Jonathan Leffler Nov 02 '12 at 05:32

2 Answers2

5

You normally want to use something like:

char command[80];

while(1)
{
    printf("input$ ");
    scanf("%79[^\n]%*c", command);
}

The '79' prevents a buffer overflow, and the %*c consumes the new-line from the input buffer. It has one minor shortcoming: it will still consume (and throw away) a character, even if the next character in the input buffer is not a new-line. If you have to deal with that possibility, you can read it and ignore it unless your command buffer is full:

char ignore;

scanf("%79[^\n]%c", command, &ignore);

if (strlen(command) == 79)
    // `ignore` probably shouldn't be ignored after all
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • +1 Perfect! @OP Check out the documentation for scanf (man scanf), it's worth the read -- it's a much more powerful function than you might think. – salezica Feb 16 '12 at 06:23
  • This has trouble when code 1) reads a line that begins with `'\n"` 2) as noted, consumes the 80th characters even if it is not a `'\n'` which could be prevented with `"%79[^\n]%*1[/n]"` – chux - Reinstate Monica Oct 02 '17 at 16:42
2

Try this:

char command[80];

while(1)
{
    printf("input$ ");
    fgets(command, 80, stdin);    
}
Anthony
  • 12,177
  • 9
  • 69
  • 105
Riskhan
  • 4,434
  • 12
  • 50
  • 76