C语言 如何将 scanf 用于字符数组输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28366157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:44:05  来源:igfitidea点击:

How to use scanf for a char array input?

carraysscanf

提问by cyis

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

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);    
}  '  

回答by Gopi

The scanf()with format specifier %sscans the input until a space is encountered. In your case, what you are seeing is undefined behavior. Your array can hold 10 chars, but you are writing out of its boundaries.

scanf()与格式说明%s,直到遇到一个空间扫描输入。在您的情况下,您看到的是未定义的行为。您的数组可以容纳 10char秒,但您正在写出它的边界。

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()处理缓冲区溢出之类的功能。

回答by Ahmad Yoosofan

You can use

您可以使用

scanf("%9s", input);