首页 > 解决方案 > 指针(char*)与整数错误的比较

问题描述

所以基本上用户在一个变量中输入他们访问过多少个国家,然后我把它作为数组的大小。

之后,我使用for循环列出所有访问过的国家。但我想让我的代码更聪明一点,并把and最后一个国家放在句末。

例如3国家:

You visited Japan, Korea and Canada.
                 ^       ^^^
#include <stdio.h>
#include <cs50.h>


int main(void)
{
    int number_of_p = get_int("How many countries did you visit?\n");
    string countries[number_of_p];

    for (int x = 0; x < number_of_p; x++)
    {
        countries[x] = get_string("What countries did you visit?\n");
    }
    printf("You visited %i countries, including: ", number_of_p);
    for (int x = 0; x < number_of_p; x++)
    {

        printf("%s, ", countries[x]);
        /* looks for last element in arrays, inserts 'and' 
        to make it look grammatically correct. */

        if (countries[x] == number_of_p - 1 ) // ERROR HERE
        {
            printf(" and ");
        }

    }
    printf(".\n");

}

我正在比较指针 ( char*) 和整数错误。

是什么char*意思?

如何访问数组中的最后一个元素?

标签: ccs50c-strings

解决方案


countries[x]is a string(其中 inCS50是 的 typedef char*),number_of_pis an int,您无法比较它们,它们是不同的类型,您可能想要比较 index x,这是您的代码的可能(和快速)修复,包括标点符号看起来像这样:

现场演示

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int number_of_p = get_int("How many countries did you visit?\n");
    string countries[number_of_p];

    for (int x = 0; x < number_of_p; x++)
    {
        countries[x] = get_string("What countries did you visit?\n");
    }
    printf("You visited %i countries, including: ", number_of_p);
    for (int x = 0; x < number_of_p; x++)
    {

        printf("%s", countries[x]);
        if(x < number_of_p - 2){
            printf(", ");
        }
   
        if (x == number_of_p - 2)
        {
            printf(" and ");
        }  
    }
    printf(".\n");
}

输入:

3
Japan
Korea
Canada

输出:

You visited 3 countries, including: Japan, Korea and Canada.

推荐阅读