除了输入" blue"完成if语句但输入" Blue"被认为是别的。我在使用||制作或声明时遇到问题所以"蓝"或"蓝"是可以接受的如果有人能提供一些指导,我将不胜感激。我刚开始学习C。
printf("What is your favorite color?\n");
scanf("%s", &color);
if (strcmp(color, "blue") == 0) {
printf("Your favorite color is %s. Me too!\n\n", color);
} else {
printf("Your favorite color is %s. That is cool. My favorite color is blue.\n\n", color);
}
完整脚本:
#include <stdio.h>
#include <string.h>
int main(void)
{
char first [20];
char last [20];
char color [20];
int n;
printf("Please input your first name: ");
scanf("%s", &first);
printf("Please input your last name: ");
scanf("%s", &last);
printf("Your name is %s %s.\n\n", first,last);
printf("What is your favorite color?\n");
scanf("%s", &color);
if (strcmp(color, "blue") == 0) {
printf("Your favorite color is %s. Me too!\n\n", color);
}
else {
printf("Your favorite color is %s. That is cool. My favorite color is blue.\n\n", color);
}
printf("I am thinking of a number between 1 and 100. Can you guess it?\n");
scanf("%d", &n);
if (n == 54) {
printf("The number is 54! That is correct!\n\n", n);
}
else {
printf("Wrong the number is not %d. The number was 54.\n\n", n);
}
printf("Your name is %s %s. Your favorite color is %s. You guessed the number %d.\n\n", first,last,color,n);
return(0);
}
答案 0 :(得分:2)
直接使用||
同时接受两者?
if (strcmp(color, "blue") == 0 || strcmp(color, "Blue") == 0)
答案 1 :(得分:2)
strcmp()
区分大小写。您可以使用逻辑OR ||
使代码与其他输入格式一起使用。例如:
if ((strcmp(color, "blue") == 0) || (strcmp(color, "Blue") == 0))
但这写起来相当繁琐,不适用于输入&#34; BLUE&#34;。
如果在基于Unix的系统上,您可以使用strcasecmp()
进行不区分大小写的比较。不幸的是,这个功能并不标准。在Windows上,等效值为stricmp()
。
答案 2 :(得分:1)
如果您不想依赖特定于平台的标题,则可以非常轻松地将整个输入字符串转换为小写:
void lower_string(char *str) {
for (char *p = str; *p != '\0'; ++p) {
*p = tolower(*p);
}
}
然后
lower_string(color);
或滚动您自己不区分大小写的比较
int strcmp_insensitive(const char *str1, const char *str2) {
for (; *str1 && *str2; ++str1, ++str2) {
if (tolower(*str1) > tolower(*str2)) return 1;
if (tolower(*str1) < tolower(*str2)) return -1;
}
if (*str1 == *str2) return 0;
if (*str1 == '\0') return -1;
return 1;
}
虽然出于简单的目的,我建议使用glampert的答案。
答案 3 :(得分:0)
B和b具有不同的char值,因此它们不相等。有一种非常强大的方法可以解决这个问题 - 在进行比较之前将整个字符串转换为大写或小写。这将确保Blue,BLUE,blue和BlUe的值相同。 我的库中有一些用于更改大小写的函数,devlib。以下是实际功能:
#include <algorithm>
#include <string>
#include <cstring>
std::string toLower(std::string line)
{
std::string tmp = line;
std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);
return tmp;
}
std::string toUpper(std::string line)
{
std::string tmp = line;
std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::toupper);
return tmp;
}
或者,您可以创建不区分大小写的函数
bool compareToIgnoreCase(std::string aString, std::string anotherString)
{
return !strcmp(toLower(aString).c_str(), toLower(anotherString).c_str());
}