简体   繁体   English

scanf()如何读取未格式化的输入?

[英]How scanf() reading unformatted input?

Explain the output in this case when string is not formatted but still scanf() is able to read integers from an input string. 在这种情况下,当字符串未格式化但scanf()仍能够从输入字符串读取整数时,请解释输出。

#include <stdio.h>
int main(void)
{
int n;
while (scanf("%d", & n))
    printf("%d\n", n);
return 0;
}

Example Input: 输入示例:

1 2 3 4 5 54 34 abcd

Output: 输出:

1
2
3
4
5
54
34

Input is so messy but output is still clean. 输入是如此混乱,但输出仍然干净。 How scanf() is working? scanf()如何工作?

For the "%d" specifier it will ignore whitespace characters, and then when it reaches the invalid characters non-digit it will return 0 , for each numeric value it returns 1 which is the number of specifiers successfully matched. 对于"%d"说明符,它将忽略空白字符,然后当到达无效字符non-digit ,它将返回0 ,对于每个数字值,它将返回1 ,这是成功匹配的说明符数目。

Read here for more information. 在这里阅读更多信息。

scanf("%d", &n)对于整数将返回1(成功读取的值数),并且在遇到非数字时将失败,并且会破坏while

scanf ignore the blank characters such as: scanf忽略空白字符,例如:

\t(ASCII:0x09) 
\n(ASCII:0x0a)
blank(ASCII:0x20)

ref: scanf 参考: scanf

Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). 空格字符:该函数将读取并忽略下一个非空格字符之前遇到的所有空格字符(空格字符包括空格,换行符和制表符-请参见isspace)。 A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none). 格式字符串中的单个空格可验证从流中提取的任意数量的空格字符(包括无空格字符)。

In c programming language data type is strictly defined . 在C语言中,严格定义了数据类型。 You have to enter proper data in scanf() function . 您必须在scanf()函数中输入正确的数据。 In you enter any wrong type then it will return 0 that means false . 输入任何错误的类型后,它将返回0,表示false。 Try to do like this . 尝试这样做。 The mechanism will be clear to you . 该机制对您很清楚。

#include <stdio.h>
int n,m;
int main()
{
    do{
        m = scanf("%d",&n);
        printf("Legality: %d  Value: %d\n",m,n);
    }while(m);
    return 0;
}

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

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