C++字符串和整数互转换
来源:互联网 发布:单片机串口转usb接线 编辑:程序博客网 时间:2024/06/06 08:46
字符串转换成整数
#include<iostream>
#include<string>
#include<stdio.h>//printf的头文件
#include <stdlib.h> //atoi的头文件
using namespace std;
int main(){
/****************字符串转换成整数*****************/
//方法一:atoi函数 字符数组转换成整数
char str1[10]="123"; //实际上4个字符
int a = atoi(str1);
printf("%d\n",a);
/*
string str2="12345";
int b=atoi(str2);
这种写法错误,()内必须是字符型数组
*/
//方法二:求和法
char arr[]={'4','3','5','1','\0'};
int i=0,temp,sum=0;
while(arr[i]){
temp = arr[i]-'0';
sum = sum*10+temp;
i++;
}
printf("%d\n",sum);
}
整数转换成字符串
#include<iostream>
#include<string>
#include <stdlib.h> //itoa的头文件
using namespace std;
int main(){
/****************整数转换成字符串*****************/
//方法一:itoa函数
int num1=521;
char str1[10]; //实际上4个字符
itoa(num1,str1,10);
cout<<str1<<endl;
//方法二:将整数的每位转换为字符,然后再逆序保存
int num=435,i=0,j=0;
char temp[7],str[7];
//将整数的每位转换为字符
while(num){
temp[i]=num%10+'0';
i++;
num=num/10;
}
temp[i] = 0; //最后加上字符串结束符'\0'
//cout<<temp;输出结果是534
//逆序保存
i--;
while(i>=0){
str[j]=temp[i];
i--;
j++;
}
str[j]=0; //最后加上字符串结束符'\0'
cout<<str;//输出结果是435
}
#include<iostream>
#include<string>
#include<stdio.h>//printf的头文件
#include <stdlib.h> //atoi的头文件
using namespace std;
int main(){
/****************字符串转换成整数*****************/
//方法一:atoi函数 字符数组转换成整数
char str1[10]="123"; //实际上4个字符
int a = atoi(str1);
printf("%d\n",a);
/*
string str2="12345";
int b=atoi(str2);
这种写法错误,()内必须是字符型数组
*/
//方法二:求和法
char arr[]={'4','3','5','1','\0'};
int i=0,temp,sum=0;
while(arr[i]){
temp = arr[i]-'0';
sum = sum*10+temp;
i++;
}
printf("%d\n",sum);
}
整数转换成字符串
#include<iostream>
#include<string>
#include <stdlib.h> //itoa的头文件
using namespace std;
int main(){
/****************整数转换成字符串*****************/
//方法一:itoa函数
int num1=521;
char str1[10]; //实际上4个字符
itoa(num1,str1,10);
cout<<str1<<endl;
//方法二:将整数的每位转换为字符,然后再逆序保存
int num=435,i=0,j=0;
char temp[7],str[7];
//将整数的每位转换为字符
while(num){
temp[i]=num%10+'0';
i++;
num=num/10;
}
temp[i] = 0; //最后加上字符串结束符'\0'
//cout<<temp;输出结果是534
//逆序保存
i--;
while(i>=0){
str[j]=temp[i];
i--;
j++;
}
str[j]=0; //最后加上字符串结束符'\0'
cout<<str;//输出结果是435
}
阅读全文
1 0
- c 字符串 整数转换
- 字符串和整数转换
- C++字符串和整数互转换
- c语言字符串整数转换
- 整数和字符串之间转换
- c++整数和字符串转换
- 【C/C++】字符串转换成整数
- C学习笔记 10 字符串转换整数
- 将C字符串转换为整数
- c 把一整数转换为字符串
- c语言中的字符串转换成整数
- C:atoi 字符串转换成整数
- C语言中将字符串转换为整数
- c语言,字符串转换成整数
- 整数转字符串和字符串转换为整数
- C语言 整数字符串转换成int整数
- C语言atoi()函数:将字符串转换成int(整数)和sprintf和memset
- 字符串和16进制整数转换
- 阿里大于手机验证码
- Java如何获取方法参数的参数名称?
- Linux-一些好用的命令
- docker安装(ubuntu环境)
- 13章php上传文件
- C++字符串和整数互转换
- 剑指offer之数组中出现次数超过一半的数字
- AngularJS
- 斯坦福李飞飞-深度学习与计算机视觉 数据驱动的图像分类方式:K最近邻与线性分类器
- Fastjson使用 -- 序列化和反序列化的时候日期处理
- 网页练习之仿百度首页
- 设计模式之----工厂方法模式
- Android Camera2 Mediacodec编码
- tensorflow--tf.cast()