关于数字转为字符串(itoa)和字符串转为数字(atoi)介绍及使用

头文件是   #include<stdlib.h>

有几个:

atoi : 字符串转换为整型

atof : 字符串转换为双精度浮点型值

itoa : 整型转换为字符串

Itoa : 长整型转字符串


一、atoi

atoi : a(char,字符) to int,字符串转整型。

例子:

#include <cstdio>  
#include <stdlib.h> 
#include <cstring> 
#include<iostream> 
using namespace std;
  
int main(void)  
{  
    int num;
    char str[12];
    gets(str);
    num = atoi(str);
    printf("%d\n", num);  
    
    return 0;  
}
这里的atoi(str),是一个字符数组,也就是字符串。


二、itoa

itoa : 整型转为字符串。

itoa()函数的原型为: char *itoa( int value, char *string,int radix);

itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转换数字时的进制数。例如:转换进制为10,即将一个数变为字符串存是用10进制表示的。

例子:

#include <cstdio>  
#include <stdlib.h> 
#include <cstring> 
#include<iostream> 
using namespace std;
  
int main(void)  
{  
    int num = 8;
    char str[12];
    itoa(num,str,10);
    printf("%s\n", str);  
    itoa(num,str,2);
    printf("%s\n", str);
    return 0;  
}  
所以第一个输出应该是8的10进制字符串,第二个输出是8的2进制的字符串。


三、综合使用

如果要将一个10进制的数转为其他进制的数输出(输出也要是整型)。

思路,先将整型变为字符串的其他进制,然后将字符串转为整型进行输出即可。

#include "stdio.h"  
#include "stdlib.h"  
  
int main(void)  
{  
    int num = 15;  
    char str[100];  
    int n = atoi(itoa(num, str, 2));   //先把num转换为二进制的字符串,再把该字符串转换为整数  
    printf("%d\n",n);  
    system("pause");  
    return 0;  
}
最后输出的n应该是个整型数(%d),但表示的是15的2进制的表达。







猜你喜欢

转载自blog.csdn.net/mikchy/article/details/79127890