数字字符串上的STRCMP

数字字符串上的STRCMP,c,strcmp,C,Strcmp,所以我有3个变量: char fromAge[4]; char toAge[4]; char age[4]; 它们都可以有一个介于18和100之间的数字,包括18和100。 当我给他们下列值时,出于某种原因,以下陈述是错误的: fromAge[4] = 18; toAge[4] = 100; age[4] = 25; if (strcmp(age, fromAge) >= 0 && strcmp(age, toAge) <= 0) { //actions } 年龄

所以我有3个变量:

char fromAge[4];
char toAge[4];
char age[4];
它们都可以有一个介于18和100之间的数字,包括18和100。 当我给他们下列值时,出于某种原因,以下陈述是错误的:

fromAge[4] = 18;
toAge[4] = 100;
age[4] = 25;
if (strcmp(age, fromAge) >= 0 && strcmp(age, toAge) <= 0)
{
//actions
}

年龄是2,5,'\0'

你在检查字符串,这意味着你在按字母顺序检查它,事实上:2在字母表中不在1之前:在ASCII中,2的值是50,而1的值是49,事实上:50不在49之前

因此,使用数字作为字符串总是一个坏主意,只需将它们视为数字,一切都应该很好:

int FromAge;
int ToAge;
...
好运

strcmp通过从左到右比较单个字符来比较字符串,一旦两个字符不同,它就会返回。由于字符“1”小于字符“2”,因此字符串100将被视为小于字符串25

试试这个代码,输入100和25

int main()
{
  char toAge[4] = {0};
  char age[4]={0};
  scanf("%3s", age);
  scanf("%3s", toAge);

  // Using string compare
  if (strcmp(age, toAge) < 0)
    printf("\"%s\" is less than \"%s\"\n", age, toAge);
  else if (strcmp(age, toAge) > 0)
    printf("\"%s\" is greater than \"%s\"\n", age, toAge);
  else
    printf("\"%s\" is equal to \"%s\"\n", age, toAge);

  // Using integer compare
  if (atoi(age) < atoi(toAge))
    printf("%s is less than %s\n", age, toAge);
  else if (atoi(age) > atoi(toAge))
    printf("%s is greater than %s\n", age, toAge);
  else
    printf("%s is equal to %s\n", age, toAge);

  return 0;
}

正如您所见,函数atoi可用于获得预期结果。

C中的索引从0开始。所以fromAge[4]并不存在。定义的fromAge[4]仅从fromAge[0]到fromAge[3]等等。这不是为字符数组分配数值的方式。使用atoi
int main()
{
  char toAge[4] = {0};
  char age[4]={0};
  scanf("%3s", age);
  scanf("%3s", toAge);

  // Using string compare
  if (strcmp(age, toAge) < 0)
    printf("\"%s\" is less than \"%s\"\n", age, toAge);
  else if (strcmp(age, toAge) > 0)
    printf("\"%s\" is greater than \"%s\"\n", age, toAge);
  else
    printf("\"%s\" is equal to \"%s\"\n", age, toAge);

  // Using integer compare
  if (atoi(age) < atoi(toAge))
    printf("%s is less than %s\n", age, toAge);
  else if (atoi(age) > atoi(toAge))
    printf("%s is greater than %s\n", age, toAge);
  else
    printf("%s is equal to %s\n", age, toAge);

  return 0;
}
"100" is less than "25"
100 is greater than 25