在这段代码中,在为前两个 scanf 函数提供输入之后。输出会自动显示。我学会了这种形式的 scanf for string。但它并没有专门等待它。有什么建议 ?
#include <stdio.h>
int main()
{
int p;
int q;
char kog[50];
scanf("%d",&p);
scanf("%d",&q);
scanf("%50[^ ]s",kog);
printf("%d %d %s",p,q,kog);
return 0;
}
最佳答案
什么意思:
scanf("%50[^ ]s",kog);
?
如果你想扫描直到打印出新行,尝试:
scanf(" %49[^\n]",kog);
顺便提一下,宽度说明符 1 总是小于字符串的大小。这是为了避免覆盖终止空字符。所以提到 49 而不是 50 作为宽度说明符。
来自 cppreference :
If width specifier is used, matches only up to width. Always stores a null character in addition to the characters matched (so the argument array must have room for at least width+1 characters).
另请注意,扫描集转换在 ]
处完成。结构是"%49[…]"
,仅此而已。一个常见的误解是扫描集后面应该跟s
。
并在 scanf()
中的 %
之前提供一个空格,以避免消耗在上一个条目末尾输入的换行符。
关于c - Scanf 函数不等待字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41763941/