把字符串转换为整数
来源:互联网 发布:小班亲子美工纸盘教案 编辑:程序博客网 时间:2024/05/22 00:28
C语言的库函数atoi()的作用是将一个字符串转换为整数。写一个函数StrToInt,实现这一功能。
-
-
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
-
-
-
-
-
- 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)=='-')
- {
- isFirst=false;
- hasMinus = true;
- p++;
- continue;
- }
- else if (isFirst && (*p)=='+')
- {
- p++;
- isFirst=false;
- continue;
- }
-
- if ((*p) >='0' && (*p) <= '9')
- {
- nInt = nInt * 10 + (*p) - '0';
- if ((!hasMinus && nInt>0x7FFFFFFF) || (hasMinus && nInt<(signed int)0x80000000))
- {
- 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;
- }
运行结果:
说明:在判断上溢、下溢时出现错误!不知缘由,请大牛指正!
转载:http://blog.csdn.net/htyurencaotang/article/details/9883879