gpt4 book ai didi

c - 关于使用 scanf 读取字符串

转载 作者:行者123 更新时间:2023-11-30 17:39:59 26 4
gpt4 key购买 nike

当我使用 scanf() 从键盘读取字符串时,该字符串被声明为

char str[ 10 ];

,我应该使用%10s还是%9s来正确限制输入的字符数?提前致谢。

最佳答案

should I use %10s or %9s to properly limit the number of characters input?

可以使用但更好使用fgets读取字符串。

 fgets(str, 10, stdin);  

复制到 str 的 9 个字符后会自动附加终止空字符。

7.21.7.2 fgets 函数

Synopsis

#include <stdio.h>
char *fgets(char * restrict s, int n,
FILE * restrict stream);

Description
The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

关于c - 关于使用 scanf 读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21647971/

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