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$
2
  • You're better off just avoiding scanf. c-faq.com/stdio/scanfprobs.html Commented Feb 16, 2012 at 6: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. Commented Nov 2, 2012 at 5:32

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

+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.
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]"
2

Try this:

char command[80];

while(1)
{
    printf("input$ ");
    fgets(command, 80, stdin);    
}

2 Comments

I second Jerry. I think this is bad advice.
@Lucas: see stackoverflow.com/questions/1694036/…. Note that the updated answer (using fgets) is okay.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.