簡體   English   中英

將字符串轉換為數字並返回到字符串

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

我有一個字符串,例如"23:0" ,它是一個小時格式。 例如,我需要將其轉換為 int,以便我可以為其添加時間。 我有一個字符串"23:0"我需要添加 6 個小時,這將是"6:0"然后給我"5:0" ,然后將其轉換回字符串。

任何想法將不勝感激:)


當我編寫我的函數時,出現錯誤“無法在初始化中將 '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

由於字符串采用特定格式 ([hour]:[min]),您可以使用sscanf()來掃描字符串。 由於字符串采用預期格式,因此這將是最容易做到的。 否則,您將使用其他人描述的其他方法。

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

之后,您可以進行所需的數學運算並將結果返回到緩沖區。

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

標准庫中有針對這些簡單任務的簡單函數。 查找atoi()atof()用於字符串到數字的轉換,以及sprintf()用於數字到字符串的轉換。

編輯:示例。 代碼:

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

標准輸出:

Result: 5

干杯!

聽起來您需要同時完成幾件事(盡管這聽起來確實像是一項家庭作業)。 非常基本的例子是:

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

至少有一些類似的東西,寫在我的頭上,所以提前為任何拼寫錯誤/語法錯誤道歉;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM