【问题标题】:i get this error "solution.c:9:4: warning: implicit declaration of function 'stricmp' [-Wimplicit-function-declaration] x= stricmp(ap,c);"我收到此错误“solution.c:9:4: 警告:函数‘stricmp’的隐式声明 [-Wimplicit-function-declaration] x=stricmp(ap,c);”
【发布时间】:2016-05-25 21:47:25
【问题描述】:
 #include<stdio.h>
 #include<stdlib.h>
 #include<string.h>
 #include<time.h>
 int main()
 {
             int hh,mm,ss;
             char ap[2];
             scanf("%d%d%d%s",&hh,&mm,&ss,ap);
             if(stricmp(ap,"AM")!=0)
             {
                   hh+=12;

              }
              printf("%d:%d:%d",hh,mm,ss);
              return 0;
            ## 

此代码将 12 小时制时钟格式转换为 24 小时制时钟格式

##}

【问题讨论】:

  • 旁白:char ap[2]; 太短了。它不能保存以 nul 结尾的字符串 "AM"
  • 感谢您的评论。因此,在字符串中,为空字符分配了 1 个额外的内存位置,因为字符串附加了“/0”
  • 没错,如果你输入am来满足%s格式写入ap[2]你会导致缓冲区溢出。
  • stricmp 不是标准的。在 Linux 上使用 strcasecmp 或在 Windows 上使用 _stricmp
  • @nishchalpro 抱歉:这就是为什么它被发布为“旁白”评论,而不是答案。

标签: c


【解决方案1】:

字符串空间不足。还增加了扫描限制

char ap[3];
scanf("%d%d%d%2s",&hh,&mm,&ss,ap);

stricmp 不是标准的。在 Linux 上使用 strcasecmp 或在 Windows 上使用 _stricmp

功能上缺少对时间的处理,例如 12 34 56 AM,应该更改为 0 34 56。

if(stricmp(ap,"AM")==0) {
  if (hh >= 12) hh -= 12;
} else if(stricmp(ap,"PM")==0) {
  hh +-= 12;
}

更常见的是打印带有前导零的分钟.秒。

printf("%d:%02d:%02d",hh,mm,ss);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多