题目摘录于各大IT公式笔试面试题及网络,本人为编程菜鸟,欢迎各位网友批评指正。
1、字符串与整数(或小数)的转换:字符串转换为整数(小数),整数(小数)转换为字符串;
(1) 字符串转换为整数(小数),应考虑到字符串前后的空格以及正负号。
#include<iostream>
using namespace std;
int main()
{
double ch2num(char s[]);
char ch[] = " -123.455 ";
cout << ch2num(ch) << endl;
//char chc = '-';
//cout << (int)chc << endl;
return 0;
}
double ch2num(char s[])
{
int i = 0; //整数部分
double t = 0; // 小数部分
int sign = 1; // 判断符号,默认为正
while (*s == ' ') ++s;
if (*s == '-')
sign = -1, ++s;
else
if (*s == '+') sign = 1, ++s;
while (*s != '\0' && *s >= '0' && *s <= '9')
{
i = 10 * i + (*s) - '0';
++s;
}
if (*s == '.') ++s;
int k = 10;
while (*s != '\0' && *s >= '0' && *s <= '9')
{
t = t + ((*s) - '0')*1.0 / k;
k *= 10;
++s;
}
if (*s == '\0')
cout << "OK" << endl;
return sign*(i + t);
}
(2) 整数转换为字符串
#include<iostream>
#define MAXSIZE 100
using namespace std;
int main()
{
char * num2str(int);
int d = 123;
//char ch[] = " -123.455 ";
cout << num2str(d) << endl;
return 0;
}
char* num2str(int num)
{
char *ch = new char[MAXSIZE];
int i = 0;
while (num)
{
ch[i] = num % 10 + '0';
++i;
num = num / 10;
}
ch[i + 1] = '\0';
// 逆序
char *ch2 = new char[i];
--i;
int j = 0;
while (i>=0)
{
ch2[j] = ch[i];
++j, --i;
}
ch2[j + 1] = '\0';
return ch2;
}