C语言实现数字串转数字

方法一、字符相减

核心代码:arr[i]=str[i]-'0';

//数字字符转数字
#include <stdio.h>
int main()
{
    
    
	int arr[80]={
    
    0}; 				//整型数组
	char str[80]="1234531";		//数字字符数组
	int i=0;
	
 	for(i=0;str[i]!=0;i++)
 		arr[i]=str[i]-'0';
	
	for(i=0;arr[i]!=0;i++)
		printf("%d",arr[i]);

	return 0;
} 

在这里插入图片描述

方法二、atoi( )函数

示例

#include <stdio.h>
#include <string>

int main()
{
    
    
	char str[] = "2021228";
	int n = atoi(str);	
	printf("%d",n);
	return 0;
}

在这里插入图片描述

此处的str不能是string类型,否则会报错
在这里插入图片描述
如果是string类型,要么用stoi( )函数,要么用c_str( )函数从中转化

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
using namespace std;
#include <string>

int main()
{
    
    
	char c[20];
	string str = "20212208";
	strcpy(c,str.c_str());
	int n = atoi(c);
	printf("%d",n);
	return 0;
}

方法三、stoi( )函数

#include <stdio.h>
#include <iostream>
using namespace std;
#include <string>

int main()
{
    
    
	string str = "20212208";
	int n = stoi(str);
	printf("%d",n);
	return 0;
}

另:虽然有封装好的函数atoi( ),但是在编译器Dev-C++ 5.11中(vs 2019中不用),需要更改设置才能识别atoi( )函数。Dev-C++ 5.11虽是蓝桥杯指定的编译器,但如果需要更改设置才能通过,不知道能不能过OJ。所以这个方法就不打算用在蓝桥杯了。

遇到的bug

在方法一使用Dev-C++ 5.11中,发现结果有失误。检查多遍后,并未发现失误。
在这里插入图片描述
将其在vs 2019中运行,发现应是数组arr未初始化。
在这里插入图片描述

在这里插入图片描述
将arr初始化后,问题解决。

参考博客:
atio/stio
c_str

猜你喜欢

转载自blog.csdn.net/m0_51336041/article/details/121191636
今日推荐