面试题33:把字符串转换为整数
2013-09-01 20:29
316 查看
C语言的库函数atoi()的作用是将一个字符串转换为整数。写一个函数StrToInt,实现这一功能。
运行结果:
说明:在判断上溢、下溢时出现错误!不知缘由,请大牛指正!
// 写一个函数StrToInt实现将字符串转换为整数的功能.cpp : 定义控制台应用程序的入口点。 #include "stdafx.h" #include <iostream> using namespace std; //特殊情况:1.字符串为空指针或空串 //2.字符串中有非0到9的字符(负号,#,@,等等) //特别需要注意的是:还要考虑溢出的问题。正整数最大值0x7FFFFFFF,负整数最小值0x80000000 //函数功能:将字符串str转换为整数, 由参数nInt接收整数值,若转换成功返回true,否则返回false bool StrToInt(char *str, int &nInt) { if (str == "") { cout << "空串!" << endl; return false; } else if (str == NULL) { cout << "空指针!" << endl; return false; } else if ((strcmp(str, "+")==0) || (strcmp(str, "-")==0)) { cout << "字符串输入无效!" << endl; return false; } else { char *p = str; bool isFirst = true;//标记是否为字符串的第一个字符 bool hasMinus = false;//标记字符串的第一个字符是否为负号 nInt = 0; while (*p != '\0') { if (isFirst && (*p)=='-')//有负号 { hasMinus = true; p++; continue; } else if (isFirst && (*p)=='+') { p++; continue; } if ((*p) >='0' && (*p) <= '9')//当前字符为数字字符 { nInt = nInt * 10 + (*p) - '0'; if ((!hasMinus && nInt>0x7FFFFFFF) || (hasMinus && nInt<(signed int)0x80000000))//注意此处(signed int) { cout << "字符串数值溢出,输入无效!" << endl; return false; } p++; } else//当前字符为非数字字符 { cout << "字符串中包含有非数字的字符,不能转换为数字!" << endl; return false; } } if (hasMinus)//字符串有负号 { nInt = (-1) * nInt; } return true; } } int _tmain(int argc, _TCHAR* argv[]) { int nTest1 = 100000000000000; int nTest2 = -1000000000000000; if(nTest1 > 0x7FFFFFFF) { cout << "上溢!" << endl; } if (nTest2 < (signed int)0x80000000) { cout << "下溢!" << endl; } int nInt = 0; char *str = NULL; if (StrToInt("123", nInt)) { cout << nInt << endl; } if (StrToInt("", nInt))//空串 { cout << nInt << endl; } if (StrToInt(str, nInt))//空指针 { cout << nInt << endl; } if (StrToInt("-123", nInt)) { cout << nInt << endl; } if (StrToInt("+123", nInt)) { cout << nInt << endl; } if (StrToInt("-12#3@", nInt)) { cout << nInt << endl; } if (StrToInt("0", nInt)) { cout << nInt << endl; } if (StrToInt("+", nInt)) { cout << nInt << endl; } if (StrToInt("100000000000000000000000000000000000000", nInt)) { cout << nInt << endl; } if (StrToInt("-100000000000000000000000000000000000000", nInt)) { cout << nInt << endl; } system("pause"); return 0; }
运行结果:
说明:在判断上溢、下溢时出现错误!不知缘由,请大牛指正!
相关文章推荐
- 面试题33:把字符串转换为整数
- 常见C语言面试题之一:字符串代替、字符串转换整数
- 剑指offer-面试题49-把字符串转换成整数
- 程序员面试题精选100题(17)-把字符串转换成整数
- 剑指offer——面试题49:不使用atoi库函数实现把字符串转换成整数
- 微软,Google面试题 (17) —— 字符串转换成整数
- 剑指Offer:面试题49 把字符串转换成整数
- 剑指offer 面试题49 把字符串转换成整数
- (剑指Offer)面试题49:把字符串转换为整数
- 面试题49. 把字符串转换为整数
- 18. 微软面试题:输入一个表示整数的字符串,把该字符串转换成整数并输出
- 程序员面试题精选100题(17)-把字符串转换成整数[算法]
- 面试题49:将字符串转换成整数
- 【剑指Offer学习】【面试题49:把字符串转换成整数】
- 面试题49. 把字符串转换为整数
- 面试题49:把字符串转换成整数
- 笔试面试题解备忘1:字符串转换成整数
- 剑指offer - 面试题49:把字符串转换为整数
- 字符串转换成整数-微软面试题
- 《剑指Offer》面试题:将字符串转换为整数