C++字串和整數相互轉換
阿新 • • 發佈:2019-01-10
//將整數轉化為字串,並且不使用itoa函式
#include<stdio.h>
void main()
{
int n = 12345;
char temp[6] = {0};
int i = 0;
while (n)
{
temp[i++] = n % 10 + '0';//整數加上‘0’隱性轉化為char型別數
n /= 10;
}
char dst[6] = {0};
for (int j = 0; j < i; j++)
{
dst[j] = temp[i-1-j];
}
printf("%s\n", dst);
}
//將字串轉化為整數 #include<stdio.h> void main() { char temp[6] = {'1','2','3','4','5'}; int n = 0, i = 0; while (temp[i]) { n = n * 10 + (temp[i++] - '0');//隱性轉化為整數 } printf("%d\n", n); }