C:将SCANF与字符一起使用时Segfault

发布于 2025-02-06 21:34:36 字数 1488 浏览 2 评论 0 原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不知所踪 2025-02-13 21:34:37

而不是此调用中的格式字符串

scanf('%c', &piece_type ); //segfaults here
      ^^^^

您使用具有类型 int 的多重整数字符常数, 。因此,呼叫调用了未定义的行为。

您还需要使用字符串字面的字符串

scanf("%c", &piece_type ); 

,也最好在格式字符串中包含一个领先空间,

scanf(" %c", &piece_type ); 
      ^^^^

因此可以跳过输入缓冲区中的白空间字符。

Instead of the format string in this call of scanf

scanf('%c', &piece_type ); //segfaults here
      ^^^^

you are using a multibyte integer character constant that has the type int. So the call invokes undefined behavior.

You need to use a string literal

scanf("%c", &piece_type ); 

Also it is better to include a leading space in the format string like

scanf(" %c", &piece_type ); 
      ^^^^

This allows to skip white space characters in the input buffer.

北笙凉宸 2025-02-13 21:34:37

AS eric 说,您必须提供字符串(请参阅参考 int scanf(const char * format,...);

以下一个应解决您的问题:

  1. 替换'%c'带有“%c” ,因此代码应该看起来像
...
    printf("Enter piece type (k, b, p):\n");
    scanf("%c", &piece_type );
    /*other code */
...
  1. getchar()代替(参考 - int getchar(void);
...
    printf("Enter piece type (k, b, p):\n");
    piece_type = getchar();
    /*other code */
...

As Eric said, you have to provide string (see reference) int scanf ( const char * format, ... );

One of the following should solve your problem:

  1. replace '%c' with "%c" so the code should look like this
...
    printf("Enter piece type (k, b, p):\n");
    scanf("%c", &piece_type );
    /*other code */
...
  1. use getchar() instead (reference - int getchar ( void );)
...
    printf("Enter piece type (k, b, p):\n");
    piece_type = getchar();
    /*other code */
...
稀香 2025-02-13 21:34:36

scanf 的第一个参数必须是指向字符串的指针。通常,它以字符串字面形式给出,例如“%c” ,它会自动转换为指向其第一个元素的指针。

'%c'不是字符串或指针。它是一个多截面常数,实际上是 int 常数。

在编译器中启用警告,并将警告提升到错误。使用clang,以 - waste -werror 开始。使用GCC,以 -wall -werror 开始。使用MSVC,以/w3/wx 开始。

The first argument to scanf must be a pointer to a string. Most often it is given as a string literal, such as "%c", which is automatically converted to a pointer to its first element.

'%c' is not a string or a pointer to a string. It is a multicharacter constant, which is effectively an int constant.

Enable warnings in your compiler and elevate warnings to errors. With Clang, start with -Wmost -Werror. With GCC, start with -Wall -Werror. With MSVC, start with /W3 /WX.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文