一, atoi()-- 把字符串转换成整型数
考点: 字符串转换为数字时, 对相关 ASCII 码的理解.
C 实现:
- #include <ctype.h>
- #include <stdio.h>
- int atoi (char s[]);
- int main(void )
- {
- char s[100];
- gets(s);
- printf("integer=%d\n",atoi(s));
- return 0;
- }
- int atoi (char s[])
- {
- int i,n,sign;
- for(i=0;isspace(s[i]);i++)// 跳过空白符;
- sign=(s[i]=='-')?-1:1;
- if(s[i]=='+'||s[i]=='-')// 跳过符号
- i++;
- for(n=0;isdigit(s[i]);i++)
- n=10*n+(s[i]-'0');// 将数字字符转换成整形数字
- return sign *n;
- }
C++ 实现:
- #include <iostream>
- using namespace std;
- int str2int(const char *str)
- {
- int temp = 0;
- const char *ptr = str; //ptr 保存 str 字符串开头
- if (*str == '-' || *str == '+') // 如果第一个字符是正负号,
- { // 则移到下一个字符
- str++;
- }
- while(*str != 0)
- {
- if ((*str <'0') || (*str> '9')) // 如果当前字符不是数字
- { // 则退出循环
- break;
- }
- temp = temp * 10 + (*str - '0'); // 如果当前字符是数字则计算数值
- str++; // 移到下一个字符
- }
- if (*ptr == '-') // 如果字符串是以 "-" 开头, 则转换成其相反数
- {
- temp = -temp;
- }
- return temp;
- }
- int main()
- {
- int n = 0;
- char p[10] = "";
- cin.getline(p, 20); // 从终端获取一个字符串
- n = str2int(p); // 把字符串转换成整型数
- cout << n << endl;
- return 0;
- }
二, itoa()-- 把一整数转换为字符串
通过把整数的各位上的数字加 "0" 转换成 char 类型并存到字符数组中. 但是要注意, 需要采用字符串逆序的方法
来源: http://www.bubuko.com/infodetail-3295739.html