[英]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. 因此,当用户输入“退出”时,它应该停止要求其他3个输入。 however it asks me to input another "quit" probably because there are 2 %s in the format
但是它要求我输入另一个“退出”,可能是因为格式中有2%s
is there anyway around this? 有没有办法解决? EDIT: because it has to get 4 inputs in a loop, unless a quit is inputted.
编辑:因为它必须循环获得4个输入,除非输入了退出。
scanf
is a very blunt tool that is not good at talking to unstructured inputs (including humans :-) ). scanf
是一个非常钝的工具,不善于与非结构化输入(包括人:-)进行对话。 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
. 通常,如果您正在与人互动,则应从
fgets
开始阅读一行,然后将所得行分开,但是最方便,可能包括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. 这比您想象的要糟糕,因为如果您将
%d
指令提供为不可扫描的整数,它将导致阻塞。 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). 例如,如果您输入
quit now
,则第一个%s
指令将读取单词quit
但%d
now
将留在输入流中,导致scanf
返回1(一次成功的转换和分配)。 The next attempt to read a string will obtain and consume the now
; 下次读取字符串的尝试将获取并消耗
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.