c - 使用 C scanf_s 输入字符串

标签 c string scanf c11 tr24731

我一直试图自己寻找答案,但我找不到。
我想插入一部分程序,它读入像“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 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.



和:

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() )。

您的代码不提供长度参数,因此使用了其他一些数字。它无法确定它找到什么值,因此您会从代码中获得古怪的行为。您需要更像这样的东西,换行符有助于确保实际看到输出。
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/

相关文章:

c++ - C++ 中带字符串键的查找表的内存管理

string - 使用 matlab 使用 sscanf 分割字符串

c - 段错误和引用结构数组

c - 为什么链表中的头声明为指针?在遍历的时候我们什么时候可以定义指针并把head的地址赋给它呢?

java - java中的instanceof在嵌套数组列表上

c - 读取文本文件错误 : strange '\x01' '\0' '\0' '0' sequences

python - some_string 中的 empty_string - 总是正确的?

c - Scanf 一次请求两个字符串

c# - 将 C 结构移植到 C#

c - 对结构体数组进行排序或对结构体列表 C 进行排序,哪个更快?