简体   繁体   中英

Converting a String to number and Back to String

I have a String for example "23:0" which is a hour format. I need to convert this to a int so I can add time to it for example. 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.

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:

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. 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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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