C语言实现字符串和数字的转换

将数字转换为字符串

使用sprintf函数,包含在stdio.h头文件中

用法:sprintf(字符数组,数字类型,要转换的数字)

数字会转换为字符串存储在字符数组中

#include <cstdio>
using namespace std;

char s[10];

int main(void)
{
    
    
	int n = 100;
	sprintf(s, "%d", n);
	printf("%s\n", s);
	
	return 0;
}

将字符串转换为数字

使用atoi函数,包含在algorithm头文件中

用法:atoi(要转换的字符串)

返回转换后的数字

#include <cstdio>
#include <algorithm>
using namespace std;

char s[10] = {
    
    "100"};

int main(void)
{
    
    
	int n = atoi(s);
	printf("%d\n", n);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43772166/article/details/108592054