Read no more than size of string with scanf()

烂漫一生 提交于 2019-11-27 04:30:01

Your array needs to be able to hold four chars, since it must also contain the 0-terminator. With that fixed, specifying a maximal length in the format,

scanf("%3s", string);

ensures that scanf reads no more than 3 characters.

the safest way is to use

fgets(string,4,stdin);

here you can store maximum 3 characters including one space reserved for NULL ('\0') character.

anonymous

http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

use the "width" modifier;

%[*][width][modifiers]type

You should use the width modifier of scanf() and set it to be one less than the size of your string, so that you ensure that space exists for the NULL terminator.

So, if you want to store "yes", you will firstly need a bigger array than the one you have; one with size 4, 3 characters plus 1 for the null terminator. Moreover, you should instruct scanf() to read no more than size - 1 characters, where size is the length of your array, thus 3 in this case, like this:

#include <stdio.h>

int main(void)
{
     char string[4];
     scanf("%3s", string);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!