c - 传递 '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);
为什么?
解决方案
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
特别是自动跳过前导空格、换行符等等。
推荐阅读
- racket - 在多个通道上同步/选择-evt(在运行时确定的数量)
- ios - 在 Xcode 11.3 故事板和笔尖大小几乎是两倍
- vue.js - 渲染错误:materialui 中的“TypeError:无法读取未定义的属性‘smAndDown’”
- string - 我想检查是否满足 4 个条件应该发生什么
- domain-driven-design - AutoMapper 模式是否违反 DDD 原则?
- javascript - 如何在一个循环中找到多级嵌套 JSON 中的所有特定键,并为它们中的每一个更改值
- python - 与python电报机器人开始私人聊天时如何发送消息
- amazon-ec2 - Coturn AWS EC2 运行问题
- python - Python SimPy:yield env.timeout 不起作用
- dart - Dart 类声明中的操作符“=”是什么意思?