整型轉換成字串
阿新 • • 發佈:2019-01-29
本文轉載自:http://blog.csdn.net/mnorst/article/details/6622293
1,使用c語言函式
將整形數value轉換為其等價的字串
char *itoa(int value, char *string, int radix)
Parameters(引數說明)
第一個引數:value Number to be converted(將要被轉換的值)
第二個引數:string String result(轉換的結果)
第三個引數:radix Base of value; must be in the range 2 – 36(轉換的基數,取值範圍2-36。例如 radix=10表示10進位制,radix=8表示8進位制。)
返回值:與string引數相同,便於函式的巢狀呼叫
標頭檔案 stdlib.h
舉例說明:
- #include <stdlib.h>
- #include <stdio.h>
- int main()
- {
- int number = 123456;
- char string[25];
- itoa(number, string, 10);
- printf("integer = %d string = %s\n", number, string);
- return 0;
- }
2, 使用CString格式化字串
函式原型:void CString::Format( UINT nFormatID, [, argument]...);
使用方法同printf
舉例說明:
- int num = 2;
- CString str;
- str.Format("a=%d",a);
3,使用sprintf格式化字元
函式原型: int sprintf( char *buffer, const char *format [, argument] ... );
舉例說明:
- char buffer[10];
-
int num = 3;
- sprintf(buffer,"size=%d",num);
- /*整數轉化成字串*/
- char *IntToStr(int num, char str[])
- {
- int i = 0, j = 0;
- char temp[100];
- while(num)
- {
- temp[i] = num % 10 + '0'; //取模運算得到從後往前的每一個數字變成字元
- num = num / 10;
- i++;
- }
- temp[i] = 0; //字串結束標誌
- i = i - 1; //回到temp最後一個有意義的數字
- while(i >= 0)
- {
- str[j] = temp[i];
- i--;
- j++;
- }
- str[j] = 0; //字串結束標誌
- return str;
- }
- /*字串轉換為整數,僅考慮十進位制,不考慮非法字元*/
- int StrToInt(char *str)
- {
- int value = 0;
- int sign = 1;
- assert(str != NULL);
- if(*str == '-')
- {
- sign = -1;
- str++;
- }elseif(*str == '+')
- {
- str++;
- }
- while(*str)
- {
- value = value * 10 +(*str - '0');
- str++;
- }
- return sign * value;
- }
- /*字串轉換整數,考慮16進位制,10進位制,8進位制,不考慮其他非法字元*/
- int StrToIntAll(char *str)
- {
- int value = 0;
- int sign = 1;
- int radix;
- assert(str != NULL);
- if(*str == '-')
- {
- sign = -1;
- str++;
- }
- elseif(*str == '+')
- {
- str++;
- }
- //考慮不同的進位制
- if(*str == '0' && (*(str+1) == 'X' || *(str+1) == 'x'))
- {
- radix = 16;
- str += 2;
- }elseif(*str == '0')
- {
- radix = 8;
- str++;
- }else
- {
- radix = 10;
- }
- while(*str)
- {
- if(radix == 16)
- {
- if(*str >= '0' && *str <= '9')
- {
- value = value * radix + (*str - '0');
- }else
- {
- value = value * radix +(*str - 'a' + 10);
- }
- }else
- {
- value = value * radix + (*str - '0');
- }
- str++;
- }
- return sign * value;
- }