【发布时间】:2016-03-07 09:23:58
【问题描述】:
目前我用 C 语言编写了这个简单的代码,用于将天、分和秒转换为秒:
已编辑(我理解 atoi 的问题,像这样更正了吗?):
#include <stdio.h>
#include <stdlib.h>
int getseconds(char * time)
{
int seconds=0, i=0;
char buffer[3];
while (*time != '\0')
{
switch (*time)
{
case 'h': buffer[i]='\0';i=0;seconds=seconds+atoi(buffer)*3600;break;
case 'm': buffer[i]='\0';i=0;seconds=seconds+atoi(buffer)*60;break;
case 's': buffer[i]='\0';i=0;seconds=seconds+atoi(buffer);break;
case ' ':break;
default: buffer[i]=*time;i++;break;
}
time++;
}
return seconds;
}
int main()
{
char *time = "12h 4m 58s";
int seconds = getseconds(time);
printf("%d",seconds);
return 0;
}
这可以按我的意愿工作,但是没有其他方法可以做到这一点,而无需创建更多变量(例如 C#,我只需要转换“内联”。C 是否只有转换为变量而不是转换为变量的函数? “内联”)?
C# 示例:
string time = "12h 34m 58s";
int seconds = int.Parse(time.Substring(0, 2)) * 3600 + int.Parse(time.Substring(4, 2)) * 60 + int.Parse(time.Substring(8, 2));
你可以发现我猜的行数差异:)。
【问题讨论】:
-
重读问题并删除。
-
无关注释;
buffer在此代码中不包含字符串(字符串是字符序列,后跟\0);如果它后面的垃圾恰好是一个数字,那么 atoi 不会返回你所期望的。 -
@immibis 缓冲区只是一个“持有者”,因为特定的“字符串”只有 2 个数字,我不会输出它我真的需要用 \0 终止它吗?
-
atoi采用 c 风格的字符串。 c 风格的字符串以\0结尾。所以是的,它是必需的。 -
内联是什么意思?在一条线上?如果是这样,那么在 C# 中进行了很多类型推断,而您在 C 中无法进行(出于显而易见的原因)。除了 C 字符串不是真正的字符串,而是由 \0 终止的字符数组这一事实之外。 C# 中的 time.Substring 本身可能与您的 getseconds 函数具有相同数量(或更多)的代码。
标签: c type-conversion