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

标签 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

最佳答案

尝试使用:

#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);

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

关于c - 如何从字符串中提取整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55991853/

相关文章:

c - scanf 不读取输入

c - 从用户空间访问 i2c 扩展器的 GPIO 引脚

C程序在Netbeans中编译,但在cmd中用gcc无法编译

c - 网络编程常用的函数/代码片段有哪些?

c - scanf 跳过扫描字符

C:通过检查 2 个值创建有序列表

C编程: allocating memory for char array using malloc in C89

c++ - 生成一个数的所有因数分解

使用 fork() 的并发进程

c - 如何在 C 中将动态指针数组初始化为 NULL?