gpt4 book ai didi

c - C 中的 strcmp() 有问题

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:25 25 4
gpt4 key购买 nike

<分区>

我已经为此工作了几个小时,它是为了测试我的理智。

作业是编写一个程序,当它读取一个名称时,它会检查给定结构的名称并查找匹配项,然后显示结构中的其他数据。不管输入字符串的大小写如何,它都应该工作,如果没有匹配名称它应该告诉用户。

当然一切都编译得很好,但是当我输入一个应该命中的名字时(因为它在结构中)它看不到它。

我知道问题出在 strcmp 调用中。

如有任何帮助,我们将不胜感激。

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>



typedef struct solar
{
char name[50];
char type[50];
double radius;
double mass;
double distsun;

}solar_obj;

void main()
{
char input_name[50];

solar_obj solarobj[] = { { "CERES", "DWARF PLANET", 471, 9.5E20, 413.7E6 },
{ "EARTH", "PLANET", 6380, 5.974E24, 149.6E6 },
{ "ERIS", "DWARF PLANET", 1163, 1.7E22, 10210E6 },
{ "HAUMEA", "DWARF PLANET", 650, 4E21, 6484E6 },
{ "JUPITER", "PLANET", 71500, 1.899E27, 778.4E6 },
{ "MAKEMAKE", "DWARF PLANET", 715, 2.2E21, 6850E6 },
{ "MARS", "PLANET", 3400, 6.419E23, 227.9E6 },
{ "MERCURY", "PLANET", 2440, 3.302E23, 57.9E6 },
{ "NEPTUNE", "PLANET", 24770, 1.024E26, 4498.3E6 },
{ "PLUTO", "DWARF PLANET", 1184, 1.3E22, 5906.4E6},
{ "SATURN", "PLANET", 60270, 5.685E26, 1426.7E6 },
{ "SUN", "STAR", 696000, 1.9891E30, 0 },
{ "URANUS", "PLANET", 25560, 8.685E25, 2870.9E6 },
{ "VENUS", "PLANET", 6050, 4.869E24, 108.2E6 }
};

printf("Please enter the name of the solar object:");

fgets(input_name, sizeof(input_name), stdin);

//to make all inputed string chars into uppercase
for (int i = 0; input_name[i] != '\0'; i++){
input_name[i] = toupper(input_name[i]);
}

//search through struct for matching name then print the data
for (int j = 0; j < 14; j++)
{
if (strcmp(solarobj[j].name, input_name) == 0)
{
printf("\nObject name is : %s \n", solarobj[j].name);
printf("%s is a %s \n", solarobj[j].name, solarobj[j].type);
printf("Radius (km) : %f \n ", solarobj[j].radius);
printf("Mass (kg) : %f\n", solarobj[j].mass);
printf("Distance from sun (km) : %f \n", solarobj[j].distsun);
}

else // if a name that doesnt match anything in the struct tell the user
{
if (j == 13){
printf("No objects in our solar system have the name: %s\n", input_name);
break;
}

continue;
}
}


getch();
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com