以字符串形式输入时间,如何转化为时分秒的整型

bcai_yuan 2017-11-16 03:31:54
我想在命令框中输入时间,然后以整型数提取出时分秒,下面的程序输入完时间后运行就停止工作了,但是哪里出了问题呢?求大神们指导啊
#include <iostream>
#include <string>
#include <stdlib.h>
#include <algorithm>
#include<fstream>
#include <graphics.h> // 绘图库头文件,绘图语句需要
#include <conio.h> // 控制台输入输出头文件,getch()语句需要
int main()
{
initgraph(758, 645);
char time1[50];
int h1, m1, s1;
char **t;
int k=0, a=0, j=0;
InputBox(time1, 50, "请输入上机时间", "欢迎使用");
for(j=0; time1[j] != '\0'; j++){
if(time1[j] != ':'){
t[k][a] = time1[j];
a++;
}
else {
k++;
t[k][a] = '\0';
a=0;
}
}
h1 = atoi(t[0]);
m1 = atoi(t[1]);
s1 = atoi(t[2]);
}
...全文
728 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2017-11-24
  • 打赏
  • 举报
回复
这个碉堡了,一个指针都没有任何指向就敢写东西进去……
char **t;
t[k][a] = ...;
bcai_yuan 2017-11-16
  • 打赏
  • 举报
回复
哈哈哈,不会的,非常感谢@自信男孩
bcai_yuan 2017-11-16
  • 打赏
  • 举报
回复
解决了,太感谢了!
paschen 版主 2017-11-16
  • 打赏
  • 举报
回复
你的t只是一个指针,并没有指向有效的内存,你就去访问他(t[k][a] = time1[j];),当然导致崩溃
Intel0011 2017-11-16
  • 打赏
  • 举报
回复
char **t; ---> char t[3][12]; char **t; t为指针,你未为t分配内存,不能使用t[k][a] k++; t[k][a] = '\0'; a=0; 最后改为 t[k][a] = '\0'; k++; a=0;
自信男孩 2017-11-16
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
#include <stdlib.h>
#include <algorithm>
#include<fstream>

#include <graphics.h> // 绘图库头文件,绘图语句需要
#include <conio.h> // 控制台输入输出头文件,getch()语句需要
int main()
{
    initgraph(758, 645);
    char time1[50];
    int h1, m1, s1;
    char **t = NULL;

    t = (char **)malloc(sizeof(char *) * 3);    /* 3: 时分秒*/
    if (!t)
        return -1;
    for (int i = 0; i < 3; i++) {
        t[i] = (char *)malloc(sizeof(char) * 3);   /*时分秒字符串,至少是3,因为小时,分钟,秒都是2位数*/
        if (!t[i])
            return -1;
    }

    int k=0, a=0, j=0;
    InputBox(time1, 50, "请输入上机时间", "欢迎使用");
    for(j=0; time1[j] != '\0'; j++){
        if(time1[j] != ':'){
            t[k][a] = time1[j];
            a++;
        }
        else {
            k++;
            t[k][a] = '\0';
            a=0;
        }
    }
    h1 = atoi(t[0]);
    m1 = atoi(t[1]);
    s1 = atoi(t[2]);

    for (int i = 0; i < 3; i++)
        free(t[i]);
    free(t);

    return 0;
}
野指针导致的程序崩溃; t需要事先申请空间; 参考一下; 另外,你的帖子还没通过审核,我都给回复了。CSDN会不会找我的麻烦

64,644

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧