简体   繁体   中英

How can I make scanf() with multiple inputs ignore the others?

scanf("%s %d %s %d",word1,&num1,word2,&num2);

so when the user inputs "quit", its supposed to stop asking for the other 3 inputs. however it asks me to input another "quit" probably because there are 2 %s in the format

is there anyway around this? EDIT: because it has to get 4 inputs in a loop, unless a quit is inputted.

scanf is a very blunt tool that is not good at talking to unstructured inputs (including humans :-) ). In general, if you are interacting with a person, you should start with fgets to read a line, then pick the resulting line apart however is most convenient, possibly including sscanf .

It's worse than you think because the %d directive will jam up if you feed it something that is not scan-able as an integer. For instance, if you enter quit now , the first %s directive will read the word quit but the %d will leave now in the input stream, causing scanf to return 1 (one successful conversion-and-assignment). The next attempt to read a string will obtain and consume the now ; to naive code, this will seem like it was a later, second input line, rather than a continuation of the first one.

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

scanf("%s ", word1);
if (strcmp(word1, "quit") != 0)
    scanf("%d %s %d", &num1, word2, &num2);

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