gpt4 book ai didi

c - scanf 何时将 '\0' 附加到用户输入?

转载 作者:行者123 更新时间:2023-11-30 18:33:40 25 4
gpt4 key购买 nike

我知道 scanf("%s",arr); 会自动将 '\0' 附加到用户输入中。但我以为也仅限于此。然而,即使 scanf("%[^\n]",arr); 也会附加一个 '\0'。(我知道这会扫描所有字符,直到到达换行符)。在这种情况下,会将 '\0' 添加到 '\n' 之后或 '\n' 之前。另外,我们如何确定何时以及何时不添加 '\0' ?我们如何扫描多个字符以形成字符数组而不是字符串?

最佳答案

Also how do we figure out when and when not '\0' will be appended?

scanf是一个标准函数,我们从 C 标准中算出来。来自 C11 draft 7.21.6.2p12 :

s
... the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically. ...

[
... the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically. ...

还有更好看且常用于快速引用的 cppreference网站。

我强烈建议您永远不要使用 %s%[没有指定“最大字段宽度”的数字(除非您知道可以使用它)。始终使用%<number>s%<number>[ ,限制读取的字符数并防止溢出。所以总是:

char arr[20];
scanf("%19s", arr);

scanf这种方式是非常不安全的函数,读取字符串时很容易出现堆栈溢出。

How do we scan many characters to just form a character array and not a string?

我想你想要:

size_t fread(void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);

The fread function reads, into the array pointed to by ptr, up to nmemb elements whose size is specified by size, from the stream pointed to by stream.

它将显示 nmemb尺寸元素sizeptr指向的内存。所以只是:

 char character_array[20];
size_t number_of_chcaracter_read = fread(character_array, 20, 1, stdin);

它不会将终止空字节附加到 character_array .

关于c - scanf 何时将 '\0' 附加到用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55392155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com