Reading string with spaces using scanf? [duplicate

2019-01-19 08:24发布

问题:

This question already has an answer here:

  • Reading string from input with space character? [duplicate] 14 answers

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$

回答1:

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


回答2:

Try this:

char command[80];

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


标签: c string scanf