atoi() 和 itoa()这两个函数有的系统不支持,很多oj也不支持,OIer慎用
字符数组转整数——atoi()
输入类型:字符数组
输出类型:int 整数
//atoi需要引入stdlib.h头文件
#include <stdlib.h>
char s[10];
int num;
cin >> s;
num=atoi(s); //ascii to int
整数转字符串——itoa()
输入类型:int 整数
输出类型:字符数组
//itoa需要引入stdlib.h头文件
#include <stdlib.h>
char s[10];
int num;
cin >> num;
//把数字以十进制的形式转换为字符数组,存入s
//int to ascii
itoa(num, s, 10);
来看一道题
连乘取余问题 http://www.code-fans.cn/problem/53
输入样例
173599 3
输出样例
091
#include <bits/stdc++.h>
using namespace std;
int x, y, num, ans=1;
char s[10];
int main()
{
cin >> x >> y;
num=pow(10,y);
for(int i=0; i<x; ++i){
ans*=2011;
ans%=num;
}
//将整数以10进制方式转换为字符数组
itoa(ans, s, 10);
//输出缺少的0
if(strlen(s)<y){
y=y-strlen(s);
while(y--){
cout << "0";
}
}
cout << s;
return 0;
}
本地windows能过,但提交到oj上会出错
所以比赛时还是慎用。
要用还得用sprintf(),下面代码就能过了。
#include <bits/stdc++.h>
using namespace std;
int x, y, num, ans=1;
char s[10];
int main()
{
cin >> x >> y;
num=pow(10,y);
for(int i=0; i<x; ++i){
ans*=2011;
ans%=num;
}
//将整数ans转换为字符数组s
sprintf(s, "%d", ans);
//输出缺少的0
if(strlen(s)<y){
y=y-strlen(s);
while(y--){
cout << "0";
}
}
cout << ans;
return 0;
}
整数转字符数组——sprintf()
#include <bits/stdc++.h>
using namespace std;
char s[20];
int num;
int main()
{
cin >> num;
sprintf(s, "%d", num);
for(int i=0; i<strlen(s); ++i){
cout << s[i] << " ";
}
}