简体   繁体   English

格式字符串中的空格(scanf)

[英]whitespace in the format string (scanf)

Consider the following code: 考虑以下代码:

#include<stdio.h>
int main() {
    int i=3, j=4;
    scanf("%d c %d",&i,&j);
    printf("%d %d",i,j);
    return 0;
}

It works if I give 2c3 or 2 c 3 or 2c 3 as input if I have to change the value of variables. 如果我必须更改变量的值,则当我输入2c32 c 32c 3作为输入时,它将起作用。 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 %dc %d ? 如果我希望用户输入与我想要的相同的模式,该怎么办意味着如果%dc%d只能接受2c3而不是2 c 3 ,反之亦然,如果它是%dc %d则相反?

Whitespace in the format string matches 0 or more whitespace characters in the input. 空白格式字符串匹配在输入0或多个空格字符。

So "%dc %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 ,然后是任意数量的空白字符,最后是另一个数字。

"%dc%d" expects number, c , number. "%dc%d"期望数字c


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 %*c =读取1个字符,但不要将其分配给任何变量

So you can use "%d%*cc%*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. 因此,如果要强制用户输入,可以使用"%d%*cc%*c %d" :数字,至少1个字符,后跟任意数量的空白字符, c ,至少1个字符,后跟任意数量的空白再次输入空格字符和数字。

If you want to accept 1c2 but not 1 c 2 , use the pattern without the space: 如果要接受1c2而不是1 c 2 ,请使用不带空格的模式:

scanf("%dc%d", &x, &y);

If you want to accept 1c2 and 1 c 2 (and also 1 \\t \\tc \\t 2 etc), use the pattern with the space: 如果要接受1c21 c 2 (以及1 \\t \\tc \\t 2等),请使用带有空格的模式:

scanf("%d c %d", &x, &y);

If you want to accept 1 c 2 but not 1c2 , add a fake string containing whitespace: 如果要接受1 c 2而不是1c2 ,请添加包含空格的假字符串:

scanf("%d%*[ \t]c%*[ \t]%d", &x, &y);

Here the format string %[ \\t] would mean "read a string that contains any number of space and tab characters"; 这里的格式字符串%[ \\t]表示“读取了包含任意数量的空格和制表符的字符串”; but using the additional * , it becomes " expect a string that contains any number of space and tab characters; then discard it " 但是使用附加的* ,它将变成“ 期望包含任意数量的空格和制表符的字符串;然后将其丢弃

I think I would read the scanf result into different variables (ie not reuse i and j ) as "%d%s%d" . 我想我会将scanf结果读入不同的变量(即不重用ij )作为"%d%s%d" Then check the string you got from the %s and if it matches your requirements, use the other variables to overwrite i and j. 然后检查从%s获得的字符串,如果它符合您的要求,请使用其他变量覆盖i和j。

Force a string parsing first : 首先强制字符串解析:

char a[100], b[100];
scanf("%99s c %99s", a, b);

Then use sscanf() to convert the strings to int. 然后使用sscanf()将字符串转换为int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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