假设我必须输入以空格分隔的3个输入。让它为" 3 4 5"。现在,如果用户输入" 3 10 5",并且仅接受单个数字作为约束
我想在输入空间时使Scanf((在10后终止。
请帮忙。
最好使用 fget()
读取用户输入的 line 。
...使Scanf((在空间输入时终止...
scanf()
不是此任务的最佳工具。
通过 space ,我假设OP将耐受白空间,其中包括空间,选项卡。线路喂食和其他。
请记住,stdin
通常是线条缓冲的,但是要在无效的数字后停止scanf()
(大于1位数(,代码需要限制或跟踪输入的字符数量。" 10"将失败," 00"将失败," 1"将失败,7"将通过。
// read 1 `int` at a time.
// Use %n to record the offset of the scan up to that point
int left, right, n;
// +--==------ consume white-spaces
// | +-------- Record offset
// | | +------ Record `int`
// | | | +---- Record offset
int cnt = scanf(" %n%d%n", &left, &n, &right);
if (cnt == 1 && right == left + 1) {
Success();
} else {
Fail();
}
其他scanf()
方法可能以" %1[0-9]%c"
开头(测试2是一个空间(或" %1d%c"
。
使用getchar((检查它们是否仍然是一个数字以外的其他垃圾,并且是否存在终止
是否存在int main() {
int a=0,b=0,c=0;
char s;
scanf("%1d",&a);
if((s = getchar()) != ' ')
return 0;
scanf("%1d",&b);
if((s = getchar()) != ' ')
return 0;
scanf("%1d",&c);
if((s=getchar()) !='n')
return 0;
printf("na %d",a);
printf("nb %d ",b);
printf("nc %d ",c);
return 0;
}