简体   繁体   English

如何使用scanf进行char数组输入?

[英]How to use scanf for a char array input?

I set a char array of size of 10 and want to check the real size of the input permitted. 我设置了一个大小为10的字符数组,并希望检查允许的输入的实际大小。

I tested 我测试过了

123456789; 1234567890; 123456789123456789

Interestingly, all of them passed and got the right output which are 有趣的是,所有这些都通过并得到了正确的输出

123456789; 1234567890; 123456789123456789

It confused me a lot because I thought the last two are wrong input. 它让我很困惑,因为我认为最后两个是错误的输入。

Does that make sense or is it a compiler difference? 这有意义还是编译器的区别?

This is the code 这是代码

#include <stdio.h>
main()    
{    
char input[10];    
scanf("%s", input);    
printf(input);    
}  '  

The scanf() with format specifier %s scans the input until a space is encountered. 具有格式说明符%sscanf()扫描输入,直到遇到空格。 In your case, what you are seeing is undefined behavior. 在您的情况下,您所看到的是未定义的行为。 Your array can hold 10 char s, but you are writing out of its boundaries. 你的数组可以容纳10个char ,但你正在写出它的边界。

While you are getting an expected answer now, this is not always guarnateed and may instead cause a crash. 当你现在得到一个预期的答案时,这并不总是被证实,而是可能导致崩溃。

It is advisable to use a function such as fgets() takes care of buffer overflow. 建议使用诸如fgets()类的函数来处理缓冲区溢出。

您可以使用

scanf("%9s", input);    

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

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