gpt4 book ai didi

c - C 中的字符串搜索操作

转载 作者:行者123 更新时间:2023-11-30 20:56:33 25 4
gpt4 key购买 nike

我想要月份索引的值,但 k 的值是错误的。可以引起?函数有错误但找不到。

#include <stdio.h>
#include <string.h>
#define SIZE 20
int get_month(const char *str, char *array[])
{

int k;
for (k = 0; k < 12; ++k)
if (!strcmp(array[k], str)
return k ;
return 0;
}
int main()
{
char s[SIZE];
char *months[] = {"January"," February","March", "April","May","June","July","August ","September", " October"," November","December" };
int result;
printf("enter the month : ");
gets(s);
result = get_month(s,months);
if (result)
printf("%s - %d. is the month of the year.\n", s, result);
else
printf("%s invalid\n", s);
return 0;
}

最佳答案

int get_month(const char *str,int char **array)
^

显然你不应该在那里有一个int,字符串数组最好声明为char*[]所以应该是这样

int get_month(const char *str, char *array[])

当你得到索引时,你应该在答案中加 1,因为 C 中的索引从 0 开始,但人类从 1 开始计数。字符串常量中也有一些空格,这会使 strcmp.

<小时/>

完整的工作代码:

#include <stdio.h>
#include <string.h>
#define SIZE 20
int get_month(const char *str, char **array){

int k;
for (k = 0; k < 12; ++k)
if (!strcmp(array[k], str))
return k+1 ;
return 0;
}

int main(){
char s[SIZE];
char *months[] = {"January","February","March", "April","May","June","July","August","September", "October","November","December" };
int result;
printf("enter the month : ");
gets(s);
result = get_month(s,months);
if (result)
printf("%s - %d. is the month of the year.\n", s, result);
else
printf("%s invalid\n", s);
return 0;
}

查看此处:Coliru Sample

关于c - C 中的字符串搜索操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24099073/

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