gpt4 book ai didi

c - Strcmp 未将数组与字符串 "abc"进行比较

转载 作者:行者123 更新时间:2023-11-30 19:04:03 25 4
gpt4 key购买 nike

我正在尝试使用 strcmp 函数将包含“dec”“jan”等月份名称的数组与字符串“dec”进行比较,但它不起作用该程序的目的是对日期进行求和,例如,2018 年 12 月 12 日结果应显示总和为 1+2 + 1+2 + 2+0+1+8=17

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main(){
int i=0,j=0,k=0,sum=0,x1=0,x2=0;
char a[15],b[3]
printf("Enter String [Date] :");
gets(a);
for(i=0;a[i]!='\0';i++){
if(a[i]>=48 && a[i]<=57){
for(j=0;j<=9;j++){
if(a[i]==j+48)
sum=sum+j;
}
}
else if( (a[i]>=65 && a[i]<=90) || (a[i]>=97 && a[i]<=122 ) ){
b[k]=a[i];
k++;
}
}
printf("\n%d\n",sum);
for(i=0;i<=2;i++)
printf("%c",b[i]);
if(strcmp(b,"dec")==0){
x1=1;
x2=2;
printf("\n%d%d",x1,x2);
}
}

最佳答案

b 的数组大小需要增加并使用 null 终止符,如下所示:

char b[4]; // need size 4 to hold "dec"
/* other codes */
b[k] = '\0'; // put null terminator
printf("\n%d\n", sum);
printf("%s", b); // you can avoid the loop and use %s

关于c - Strcmp 未将数组与字符串 "abc"进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53032258/

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