如何修复if语句错误和“未指定字符串文字的比较结果”?

问题描述 投票:1回答:3

所以,我刚刚开始(原谅我的noob-ness),我正在使用Xcode在Mac上进行C程序。它基本上只是一个scanf(),然后是大量的if语句产生一个预定的输出。我写了它,以便Xcode编译它没有婊子,但我得到一个奇怪的“修复它”错误,当我尝试运行时没有输出。

char planet[9];

printf("Input the name of a planet\n");

 scanf("%c", &planet);

if (planet == "Earth")
    {printf("Earth is 150 million kilometers away from the sun");}

if (planet == "Mars") 
    {printf("Mars is 220 million kilometers away from the sun");} 

if (planet == ("Mercury"))
{printf("Mercury is 57 million kilometers from the sun");}

if (planet == ("Venus"))
    {printf("Venus is 108 million kilometers from the sun");}

if (planet == ("Jupiter"))
    {printf("Jupiter is 779 million kilometers from the sun");}

if (planet == ("Saturn"))
    {printf("Saturn is 1.73 billion kilometers from the sun");}

if (planet == ("Uranus"))
    {printf ("Uranus (haha) is 2.88 billion kilometers from the sun");} 

if (planet == ("Neptune"))
    {printf("Neptune is 4.5 billion kilometers from the sun");}

    return 0;

是代码本身,但我不能让它工作。

这里也是Xcode项目的链接。

https://www.facebook.com/photo.php?fbid=252616984794310&set=a.106237419432268.11635.100001380326478&type=1&theater

c xcode macos if-statement
3个回答
4
投票

planet的地址永远不会等于任何字符串文字的地址。您需要使用strcmp来比较字符串的内容,而不是比较它们的地址。


4
投票

使用strcmp你会更开心:

if (strcmp(planet, "Earth") == 0) {
    ...
}

此外,%c扫描一个字符,而不是字符串。您需要使用%s来扫描字符串。并且您需要指定最大长度以避免溢出缓冲区:

scanf("%8s", planet);

最大长度比缓冲区大小小1,因为您必须为NUL终结符留出空间。


0
投票

您正在将行星的地址与这些字符串文字的地址进行比较。因此地址将不相同。您应该比较两个字符串的内容,如下所示:

首先包括<string.h>,并在每个if语句中写这样的

if(!strcmp ( planet,"Earth" ))

由于无法直接比较c字符串,因此需要使用strcmp函数。

strcmp功能

int strcmp ( const char * str1, const char * str2 );

这个函数比较两个字符串和返回值将是:

a)零值表示两个字符串相等。

b)大于零的值表示不匹配的第一个字符在str1中的值大于在str2中的值;和

c)小于零的值表示相反。

© www.soinside.com 2019 - 2024. All rights reserved.