简体   繁体   English

将字符串转换为数字并返回到字符串

[英]Converting a String to number and Back to String

I have a String for example "23:0" which is a hour format.我有一个字符串,例如"23:0" ,它是一个小时格式。 I need to convert this to a int so I can add time to it for example.例如,我需要将其转换为 int,以便我可以为其添加时间。 I have a string "23:0" I need to add 6 hours which would be "6:0" which would then give me "5:0" , and then convert this back to a string.我有一个字符串"23:0"我需要添加 6 个小时,这将是"6:0"然后给我"5:0" ,然后将其转换回字符串。

Any ideas would be greatly appreciated :)任何想法将不胜感激:)


When I write my function I get an error "cannot convert 'string to char*' in initiliazation" my function looks like this:当我编写我的函数时,出现错误“无法在初始化中将 'string 转换为 char*'”我的函数如下所示:

int convert(String x){
    char *str = x;
    int hour; int minute;
    sscanf(str, "%d:%d", &hour, &minute);
    return hour;
}
convert(time) //time is a String for example 23:0

Since the string is in a particular format ([hour]:[min]), you can use sscanf() to scan the string.由于字符串采用特定格式 ([hour]:[min]),您可以使用sscanf()来扫描字符串。 Since the string is in an expected format, this would be the easiest to do.由于字符串采用预期格式,因此这将是最容易做到的。 Otherwise you'd use the other methods described by everyone else.否则,您将使用其他人描述的其他方法。

char *str = "23:0";
int hour, min;
sscanf(str, "%d:%d", &hour, &min);
/* hour = 23
   min  = 0
*/

After that you can do the math that you need and spit the results back out to a buffer.之后,您可以进行所需的数学运算并将结果返回到缓冲区。

char buf[100];
hour = (hour + 6) % 24;
snprintf(buf, 100, "%d:%d", hour, min);

There are simple functions for these simple tasks in the standard library.标准库中有针对这些简单任务的简单函数。 Look up atoi() and atof() for string-to-number conversion, and sprintf() for number to string.查找atoi()atof()用于字符串到数字的转换,以及sprintf()用于数字到字符串的转换。

Edit : example.编辑:示例。 Code:代码:

#include <stdlib.h>
#include <stdio.h>

int main() {

 char string[10];
 int n1, n2, result;

 n1 = atoi("23");
 n2 = 6;

 result = (n1 + n2) % 24;

 sprintf(string, "%d", result);
 printf("Result: %s\n", string);

 return 0;
}

stdout:标准输出:

Result: 5

Cheers!干杯!

Sounds like you need a few things done at once (even though this really sounds like a homework assignment).听起来您需要同时完成几件事(尽管这听起来确实像是一项家庭作业)。 The very basic example would be:非常基本的例子是:

char *x = "23.0";
char *y = "6.0";
float result = atof(x) + atof(y);
float result_24h = result % 24; // Modulo to get remainer only
char result_str[32]; // bad bad form, but good enough for this example
sprintf(result_str,"%f",result_24h);

At least something along those lines, written off the top of my head so apologies in advance for any typos/syntax errors;至少有一些类似的东西,写在我的头上,所以提前为任何拼写错误/语法错误道歉;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM