格式字符串中的空格 (scanf) [英] whitespace in the format string (scanf)
问题描述
考虑以下代码:
#include<stdio.h>
int main() {
int i=3, j=4;
scanf("%d c %d",&i,&j);
printf("%d %d",i,j);
return 0;
}
如果我必须更改变量的值,如果我将 2c3
或 2 c 3
或 2c 3
作为输入,它会起作用.如果我希望用户输入与我想要的相同的模式,我该怎么做意味着如果 %dc%d
那么只有 2c3
是可接受的,而不是 2 c 3
反之亦然,如果它是 %dc %d
?
It works if I give 2c3
or 2 c 3
or 2c 3
as input if I have to change the value of variables. What should I do if I want the user to enter the same pattern as I want means if %dc%d
then only 2c3
is acceptable and not 2 c 3
and vice versa if it is %d c %d
?
推荐答案
Whitespace 在格式字符串中匹配输入中的 0 个或多个空格字符.
Whitespace in the format string matches 0 or more whitespace characters in the input.
所以 "%dc %d"
需要数字,然后是任意数量的空白字符,然后是字符 c
,然后是任意数量的空白字符,最后是另一个数字.
So "%d c %d"
expects number, then any amount of whitespace characters, then character c
, then any amount of whitespace characters and another number at the end.
"%dc%d"
需要数字、c
、数字.
另请注意,如果您在格式字符串中使用 *
,它会禁止赋值:%*c
= 读取 1 个字符,但不要将其分配给任何变量
Also note, that if you use *
in the format string, it suppresses assignment:
%*c
= read 1 character, but don't assign it to any variable
所以你可以使用 "%d%*cc%*c %d"
如果你想强制用户输入:数字,至少 1 个字符后跟任意数量的空白字符,c
,至少 1 个字符后跟任意数量的空白字符和数字.
So you can use "%d%*c c%*c %d"
if you want to force user to enter: number, at least 1 character followed by any amount of whitespace characters, c
, at least 1 character followed by any amount of whitespace characters again and number.
这篇关于格式字符串中的空格 (scanf)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!