比较 C 中的单个字符和更多字符时发出警告[重复]

问题描述 投票:0回答:1

在我的代码中,有一个非常简单的 if 语句,要求用户同意程序将需要很长时间才能完成运行,因为用户指定的值太高。

int main() {
  char consent; // f around and find out preventer

  if (amount > AMOUNT_MAX) {
    printf("WARNING: %d exceeds AMOUNT_MAX. Continue?\n[Y]es or [N]o.");

    scanf("%c", &consent);

    if (consent == "Y") {
      quit(amount, "progname", true);
    } else {
      return EXIT_SUCCESS;
    }
  }
  return 0;
}

这些是我收到的警告:



quit.c:28:23: warning: more '%' conversions than data arguments [-Wformat-insufficient-args]

   28 |     printf("WARNING: %d exceeds AMOUNT_MAX. Continue?\n[Y]es or [N]o.");

      |                      ~^

quit.c:30:17: warning: result of comparison against a string literal is unspecified (use an explicit string comparison function instead) [-Wstring-compare]

   30 |     if (consent == "Y") {

      |                 ^  ~~~

quit.c:30:17: warning: comparison between pointer and integer ('char' and 'char *') [-Wpointer-integer-compare]

   30 |     if (consent == "Y") {

      |         ~~~~~~~ ^  ~~~

Stack Overflow 建议我使用现有的解决方案来解决此问题,但它对我不起作用。

编辑:修复它。

int main() {
  char consent; // f around and find out preventer

  if (amount > AMOUNT_MAX) {
    printf("WARNING: %d exceeds AMOUNT_MAX. Continue?\n[Y]es or [N]o.", amount); // added data argument

    scanf("%c", &consent);

    if (consent == 'Y') { // changed to single quote
      quit(amount, "progname", true);
    } else {
      return EXIT_SUCCESS;
    }
  }
  return 0;
}
c char
1个回答
0
投票

C 中的单引号之间有一个字符!

我做了一些细微的改变来测试:

#include <stdio.h>
#define AMOUNT_MAX 5

int main() {
  char consent; // f around and find out preventer
  int amount = 6;
  if (amount > AMOUNT_MAX) {
    printf("WARNING: %d exceeds AMOUNT_MAX. Continue?\n[Y]es or [N]o.", amount);

    scanf("%c", &consent);

    if (consent == 'Y') {
      printf("progname");
    } else {
      return -1;
    }
  }
  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.