您的位置:首页 > 职场人生

面试题1234转为1_2_3_4(实现itoa函数)的另一方法

2008-03-14 12:45 197 查看
其实这道题目所白了就是将整型数转化为字符型。思路和前一篇文章类似:

对整数取关于10的模,然后加上‘/0’标识符作为字符串的结束。因为在一个整形之后加上'0',系统会将隐式转为字符型。当然在C/C++库中有一个itoa函数能够实现这个功能,但若要求不调用该代码,而是自己实现,可参考如下:

代码如下:

#include<iostream>
using namespace std;

int main(void)
{
int num;
char temp[7],str[7];
int i,j;
i = 0;j = 0;
cin >> num;
while(num)
{
temp[i] = num%10 + '0';
i++;
num = num/10;
}
// or temp[i] = 0; is ok too!
temp[i] = '/0';

cout << "now the int num is converted" << temp << endl;
i = i - 1;

//processin the int to string
while(i >= 0)
{
str[j] = temp[i];
j++;
i--;
}

//or str[j] = 0; is ok too!
str[j] = '/0';

for(int k = 0; k < j-1 ; k++)
cout << str[k] <<"_";
cout << str[j-1] << endl;

return 0;
}

关于这段代码,有以下一些说明:

1.字符数组初始化问题:

字符数组有两种初始化形式:

char ch[];

ch[] = "12345";

ch[] = {'1' , '2', '3', '4' '5'};

第一种称为字符串初始化,系统会默认在结尾处添加/0作为额外的终止空字符。即这种方法初始化的ch是6维的。

第二种称为花括号初始化,单个字符并不需要添加额外的终止空字符,此时ch是5维的。

用以下代码来进行以下验证:

#include<iostream.h>

void main()
{
char ch1[] = "12345";
char ch2[] = {'1','2','3','4','5'};

cout <<"length of ch1:" << sizeof(ch1) << endl;
cout <<"length of ch2:" << sizeof(ch2) << endl;
}

运行结果为:

length of ch1:6
length of ch2:5

2.字符串end

在代码中temp[i] = 0和temp[j] = '/0';是等价的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: