使用C scanf_s的字符串输入 [英] String input using C scanf_s

查看:597
本文介绍了使用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:

除了cs[转换外,fscanf_s函数等效于fscanf 说明符适用于一对参数(除非分配抑制用 *).这些参数中的第一个与fscanf相同.该论点是 在参数列表中紧随其后的是第二个参数,其类型为 rsize_t并给出第一个参数指向的数组中的元素数 一对.如果第一个参数指向标量对象,则将其视为包含以下内容的数组: 一个元素.

The fscanf_s function is equivalent to fscanf except that the c, 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 for fscanf. That argument is immediately followed in the argument list by the second argument, which has type rsize_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 to fscanf_s with the argument stdin interposed before the arguments to scanf_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆