如何从字符串中提取整数?

时间:2019-05-05 12:18:10

标签: c

#include <stdio.h>

int convert_to_minutes(int h, int m) {
    int total_minutes;
    total_minutes = (h * 60) + m;
    return total_minutes;
}

int main(int argc, const char *argv[]) {
    //char duration[257];
    //scanf("%s", duration);

    int hours, minutes, total_minutes;
    scanf("%d:%d", &hours, &minutes);
    total_minutes = convert_to_minutes(hours, minutes);
    printf("\n%d\n0", total_minutes);

    return 0;
}

如何从字符串中提取整数? 如果像HH:MM这样传递字符串,我该如何扫描字符串的前2个字母并转换为整数,然后复制后2个字母MM并转换为整数?

测试用例:

1)输入:13:05,输出:785

2)输入:00:00,输出:0

3)输入:00:42,输出:42

2 个答案:

答案 0 :(得分:1)

感谢@Ely推荐使用sscanf

#include <stdio.h>

// Function to convert to minutes
int convert_to_minutes(int h, int m) {
    int total_minutes;
    total_minutes = (h * 60) + m;
    return total_minutes; 
}

int main(int argc, const char *argv[]) {
    char duration[257];
    scanf("%s", duration);

    int hours, minutes, total_minutes;

    sscanf(duration, "%d:%d", &hours, &minutes);

    total_minutes = convert_to_minutes(hours, minutes);
    printf("\n%d\n", total_minutes);

    return 0;
}

答案 1 :(得分:1)

尝试使用:

#include<stdio.h>

int main(){

    int hours=0,minutes=0,total_minutes=0;
    scanf("%d:%d",&hours,&minutes);

    total_minutes=(hours*60)+minutes;

    printf("%d",total_minutes);

    return 0;
    }

输入格式肯定是HH:MM,因此您可以尝试使用:

scanf("%d:%d",&hours,&minutes);

因此,您只需要扫描整数,而不是将其存储在字符串中并将其提取为整数即可。 我希望这能解决您的问题。