我一直试图自己寻找答案,但我找不到。
我想插入一部分程序,它读入像“Hello”这样的字符串并存储并可以在我想要的时候显示它,以便 printf("%s", blah);
生产 Hello
.
这是给我带来麻烦的代码部分
char name[64];
scanf_s("%s", name);
printf("Your name is %s", name);
我知道
printf
不是问题吗?在提示后输入内容后程序崩溃。请帮忙?
最佳答案
来自fscanf_s()
的规范在 ISO/IEC 9899:2011 标准的附录 K.3.5.3.2 中:
The
fscanf_s
function is equivalent tofscanf
except that thec
,s
, and[
conversion specifiers apply to a pair of arguments (unless assignment suppression is indicated by a*
). The first of these arguments is the same as forfscanf
. That argument is immediately followed in the argument list by the second argument, which has typersize_t
and gives the number of elements in the array pointed to by the first argument of the pair. If the first argument points to a scalar object, it is considered to be an array of one element.
和:
The
scanf_s
function is equivalent tofscanf_s
with the argumentstdin
interposed before the arguments toscanf_s
.
MSDN 说类似的话(
scanf_s()
和 fscanf_s()
)。您的代码不提供长度参数,因此使用了其他一些数字。它无法确定它找到什么值,因此您会从代码中获得古怪的行为。您需要更像这样的东西,换行符有助于确保实际看到输出。
char name[64];
if (scanf_s("%s", name, sizeof(name)) == 1)
printf("Your name is %s\n", name);
关于c - 使用 C scanf_s 输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23378636/