c - 指针(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*
意思?
如何访问数组中的最后一个元素?
解决方案
countries[x]
is a string
(其中 inCS50
是 的 typedef char*
),number_of_p
is 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.
推荐阅读
- python - 使用 scikit-learn 运行 k-fold 后如何访问数据集?
- ios - 为什么 JSONDecoder 为有效的 json 提供 typeMismatch
- c++ - 我想按字节单位传输数据,我认为这是关于字节序的
- python - 枕头图像方法与属性,为什么?
- api - 如何在 Azure Logic App 中获取 Api 执行时间
- android - 如何在android Studio的recyclerView中显示所有用户的帖子
- html - 2 列布局,左列有一个额外的滚动条,仅使用 css
- excel - 根据条件获取行号
- swift - 使用 NSStackView 自定义 NSView
- javascript - 警告:在 StrictMode 中不推荐使用 findDOMNode。findDOMNode 被传递了一个在 StrictMode 内的 Transition 实例