【问题标题】:When I try to input a string in C++, the program throws out a run time error当我尝试在 C++ 中输入字符串时,程序会抛出运行时错误
【发布时间】:2022-01-15 01:06:04
【问题描述】:

我正在尝试使用 scanf() 在 C++ 文件中输入字符串(编译器警告我将 scanf() 更改为 scanf_s(),所以我更改了它)。

char string[3];
scanf_s("%s", string);
printf("%s", string);

我在控制台中输入“abc”并按回车键。那么程序会抛出下面的异常

在 0x00007FF9C35B2079 (ucrtbased.dll) 处引发异常 Project1.exe: 0xC0000005: 访问冲突写入位置 0x0000008DD5D00000.

我无法找出错误。

【问题讨论】:

  • scanf_s 要求字符串缓冲区的大小为第三个参数。同样重要的是,C 字符串需要以 NUL 结尾。三个字母的单词需要四个字节来存储。
  • 您是否收到任何编译器警告?您应该将它们视为错误。
  • 不要同时标记 C 和 C++,除非询问两种语言之间的差异或交互。

标签: c++ string scanf


【解决方案1】:

这个答案或多或少特定于您显然正在使用的 Microsoft C 编译器。

你可能想要这个:

...
char string[30];                       // you probably want more more room for your string
scanf_s("%s", string, sizeof(string)); // 3rd parameter must be the size of the buffer
printf("%s", string);
...

阅读scanf_s的文档。

另一种选择是不使用scanf_s,而只使用标准scanf。因此,您需要在代码开头添加#define _CRT_SECURE_NO_WARNINGS(仅适用于 MS 编译器):

完整示例:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  char string[30];
  scanf("%s", string);
  printf("%s", string);
}

【讨论】:

  • scanf_s 已成为 C11 标准。见en.cppreference.com/w/c/io/fscanf
  • @pqnet 我不确定 Microsoft scanf_s 是否符合 C11 标准。但无论如何,许多 C 环境并没有实现这一点。
  • @pqnet 虽然微软的 scanf_s 不遵循 C11 规范
猜你喜欢
  • 1970-01-01
  • 2018-05-13
  • 2019-09-23
  • 2021-02-28
  • 2015-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
相关资源
最近更新 更多