使用C scanf_s的字符串输入

String input using C scanf_s

我一直在寻找自己的答案,但找不到。
我想插入一部分程序,该程序读取" Hello"之类的字符串并存储并在需要时显示它,以便printf("%s", blah);生成Hello

这是给我麻烦的代码部分

1
2
3
char name[64];
scanf_s("%s", name);
printf("Your name is %s", name);

我知道printf不是问题;在提示后输入内容后,程序崩溃。请帮忙吗?


根据ISO / IEC 9899:2011标准的附件K.3.5.3.2中的fscanf_s()规范:

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

您的代码未提供length参数,因此使用了其他一些数字。它并不能确定它会找到什么价值,因此您会从代码中得到怪异的行为。您需要更多类似的内容,其中的换行符可帮助确保实际看到输出。

1
2
3
4
char name[64];
if (scanf_s("%s", name, sizeof(name)) == 1)
    printf("Your name is %s\
"
, name);

我在大学课程中经常使用它,因此在Visual Studio(在VS2013中测试)中应该可以正常工作:

1
2
3
4
5
6
7
8
char name[64]; // the null-terminated string to be read
scanf_s("%63s", name, 64);
// 63 = the max number of symbols EXCLUDING '\\0'
// 64 = the size of the string; you can also use _countof(name) instead of that number
// calling scanf_s() that way will read up to 63 symbols (even if you write more) from the console and it will automatically set name[63] = '\\0'
// if the number of the actually read symbols is < 63 then '\\0' will be stored in the next free position in the string
// Please note that unlike gets(), scanf() stops reading when it reaches ' ' (interval, spacebar key) not just newline terminator (the enter key)
// Also consider calling"fflush(stdin);" before the (eventual) next scanf()

参考:https://msdn.microsoft.com/zh-cn/library/w40768et.aspx


1
2
3
4
5
6
7
8
9
10
11
#include<stdio.h>

int main()
{
  char name[64];
  printf("Enter your name:");
  gets(name);
  printf("Your name is %s\
"
, name);
 return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
    #include<stdio.h>

    int main()
    {
      char name[64];

      printf("Enter your name:");
      scanf("%s", name);
      printf("Your name is %s\
"
, name);

     return 0;
    }


您应该执行以下操作:scanf ("%63s", name);

更新:

以下代码对我有用:

1
2
3
4
5
6
7
#include <stdio.h>
int main(void) {
    char name[64];
    scanf ("%63s", name);
    printf("Your name is %s", name);
    return 0;
}

如果您使用的是Visual Studio,
转到Project properties -> Configuration Properties -> C/C++-> Preprocessor -> Preprocessor Definitions单击edit并添加_CRT_SECURE_NO_WARNINGS单击确定,应用设置并再次运行。

注意:这仅在您正在做作业或类似的工作时才有用,不建议在生产中使用。