C语言实现int转换string
#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; }
代码运行结果为:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。