#include <stdio.h> #include <stdlib.h> #include <string.h> int string2int(const char * string) { int value = 0; int index = 0; for(;string[index] >= ‘0‘ && string[index] <= ‘9‘; index ++) { value = value * 10 + string[index] - ‘0‘; } return value; } int string_reverse(char * strSrc) { int len = 0; int i = 0; char * output = NULL; char * pstr = strSrc; while(* pstr) { pstr++; len++; } output = (char *)malloc(len); if(output == NULL) { perror("malloc"); return -1; } for(i = 0; i < len ;i++) { output[i] = strSrc[len - i -1]; printf("output[%d] = %c\n",len - i -1,strSrc[len - i - 1]); } output[len] = ‘\0‘; strcpy(strSrc, output); return 0; } int int2string(int value, char * output) { int index = 0; if(value == 0) { output[0] = value + ‘0‘; return 1; } else { while(value) { output[index] = value % 10 + ‘0‘; index ++; value /= 10; } string_reverse(output); return 1; } } int main() { #if 0 char string[12] = "1234"; int value = string2int(string); printf("value = %d\n", value); #endif char string[128] = {0}; int value = 123; int2string(value, string); printf("int_to_string=============:%s\n",string); return 0; }
代码运行结果为:
时间: 2024-10-14 06:03:35