使用C scanf_s的字符串输入 [英] String input using C scanf_s
问题描述
我一直在寻找自己的答案,但找不到.
我想插入一部分程序,该程序读取"Hello"之类的字符串并存储并在需要时显示它,以便printf("%s", blah);
生成Hello
.
I've been trying to look for answer myself, but I can't find one.
I want to insert a part of the programming that reads in a string like "Hello" and stores and can display it when I want, so that printf("%s", blah);
produces Hello
.
这是给我麻烦的代码部分
Here's the code part that's giving me trouble
char name[64];
scanf_s("%s", name);
printf("Your name is %s", name);
我知道printf
不是问题;在提示后输入内容后,程序崩溃.请帮忙吗?
I know that printf
isn't the problem; the program crashes after something is input after a prompt. Please help?
推荐答案
根据ISO/IEC 9899:2011标准的附件K.3.5.3.2中的fscanf_s()
规范:
From the specification of fscanf_s()
in Annex K.3.5.3.2 of the ISO/IEC 9899:2011 standard:
除了
c
,s
和[
转换外,fscanf_s
函数等效于fscanf
说明符适用于一对参数(除非分配抑制用*
).这些参数中的第一个与fscanf
相同.该论点是 在参数列表中紧随其后的是第二个参数,其类型为rsize_t
并给出第一个参数指向的数组中的元素数 一对.如果第一个参数指向标量对象,则将其视为包含以下内容的数组: 一个元素.
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.
和:
scanf_s
函数等效于fscanf_s
,其参数为stdin
插入scanf_s
的参数之前.
The
scanf_s
function is equivalent tofscanf_s
with the argumentstdin
interposed before the arguments toscanf_s
.
MSDN说类似的话( scanf_s()
和 fscanf_s()
).
MSDN says similar things (scanf_s()
and fscanf_s()
).
您的代码未提供length参数,因此使用了其他一些数字.它并不能确定它会找到什么价值,因此您会从代码中得到怪异的行为.您需要更多类似的内容,其中的换行符可帮助确保实际看到输出.
Your code doesn't provide the length argument, so some other number is used. It isn't determinate what value it finds, so you get eccentric behaviour from the code. You need something more like this, where the newline helps ensure that the output is actually seen.
char name[64];
if (scanf_s("%s", name, sizeof(name)) == 1)
printf("Your name is %s\n", name);
这篇关于使用C scanf_s的字符串输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!