简体   繁体   中英

Problem with the %[^,] thing while using scanf for stdin

#include <stdio.h>
#include<string.h>

int main() {
    // Write C code here
    char word[20];
    char cat[20];
    printf("Enter the thing:");
    scanf("%[^,]",word);
    scanf("%[^,]",cat);
    printf("%s",word);
    printf("%s",cat);
    return 0;
}

So here's my code, it prints out the value for word, but not the value for cat?

After the first scan, , is left in the input stream. You need to add , to the matching pattern: [^,], .

Always check if scanf succeeds (in these cases, returns 1 ) and always limit the input to the number of characters you have space for in the buffer -1 , so %19[^,], in both cases here. If the second scan does not need a , skip adding that to the pattern matching.

Combining both scans:

#include <stdio.h>
#include<string.h>

int main() {
    char word[20];
    char cat[20];
    printf("Enter the thing:");

    // in this version, "cat" doesn't need to be followed by a comma
    if(scanf("%19[^,],%19[^,]", word, cat) == 2) {
        printf(">%s<\n", word);
        printf(">%s<\n", cat);
    }
    return 0;
}

Alternatively, the comma could be added to the beginning of the format for the next scanf ( ",%19[^,]" ), or the distinction is lost if the multiple scanf calls are coalesced into one.

The way %[^ works is that it keeps scanning characters until it finds one of the characters in its list (in your case that's only , , But it doesn't actually eat up that character and stays at that point. So visualizing the issue, say you enter Foo, bar, as input when prompted, scanf("%[^,]",word); will scan Foo and the file position will be moved to the start of , bar . Upon calling scanf("%[^,]",cat); , the , will immediately be seen and nothing will be scanned.

To fix this, you need to change the format string to eat up the , afterwards:

scanf("%[^,],",word); // Notice the ',' after ']'
scanf(" %[^,],",cat); /* A leading ' ' will leave out any whitespace between `,` and
                         the next string */

Example of running the fixed program:

Enter the thing:Foo, bar,
Foobar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM