首页 > 解决方案 > 传递 'strcmp' 的参数 1 使指针从整数而不进行强制转换

问题描述

char s[2];
do{
    scanf("%s", s);
}while(strcmp(toupper(s[0]), "Y") == 0);

这给了我以下错误:

warning: passing argument 1 of ‘strcmp’ makes pointer from integer without a cast [-Wint-conversion]
  }while(strcmp(toupper(s[0]), "Y") == 0);

为什么?

标签: c

解决方案


toupper()函数 case-convert 单个字符(确保它是大写或不是字母)并返回该字符。该strcmp()函数需要一个指向字符的指针,而不是字符。这就是你得到错误的原因。用作循环while (toupper((unsigned char)s[0]) != 'Y')中的条件:do … while

char s[2];
do {
    if (scanf("%1s", s) != 1)
    {
        fprintf(stderr, "Unexpected error scanning for a single character\n");
        exit(EXIT_FAILURE);
    }
 } while(toupper((unsigned char)s[0]) != 'Y');

请注意错误处理、避免缓冲区溢出以及避免使用char负数的普通值带来的麻烦。您还可以明智地使用:

char c;
do {
    if (scanf(" %c", &c) != 1)
    {
        fprintf(stderr, "Unexpected error scanning for a single character\n");
        exit(EXIT_FAILURE);
    }
 } while(toupper((unsigned char)c) != 'Y');

这使用单个字符输入。格式字符串中的前导空格并非偶然;它跳过前导空白。三个转换说明符不会跳过前导空格 — %c%[…](扫描集)和%n. 所有其他的,包括%s特别是自动跳过前导空格、换行符等等。


推荐阅读