把字符串转换成整数 C++实现

来源:互联网 发布:空间数据的差值 编辑:程序博客网 时间:2024/06/02 13:41
//============================================================================// Name        : TransStringToInt.cpp// Author      : Lee// Version     :// Copyright   : Your copyright notice// Description : Hello World in C++, Ansi-style//============================================================================#include <iostream>using namespace std;bool transStrToInt(char * str, int & result) {long res = 0;bool minus = false;if (NULL == str) {return false;}char *ch = str;if ('-' == *ch) {minus = true;ch++;} else if ('+' == *ch) {ch++;}if ('\0' == *ch) {return false;}res = 0;while ('\0' != *ch) {if (!(*ch >= '0' && *ch <= '9')) {return false;} else {res = res * 10 + *ch - '0';}ch++;}if(minus){res=-res;}if(res<-32768||res>32767){return false;}result=static_cast<int>(res);return true;}int main() {cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!int res = 0;char * str1 = "234";if (transStrToInt(str1, res)) {cout << res << endl;}char * str2 = "-234";if (transStrToInt(str2, res)) {cout << res << endl;}char *str3 = "";if (transStrToInt(str3, res)) {cout << res << endl;}return 0;}

0 0