C++ string转换成int
C++ string转换成int
1 #include <iostream> 2 #include <cstdlib> 3 #include <cctype>//isspace() 4 #include <climits>//INT_MAX INT_MIN 5 #include <string> 6 using namespace std; 7 8 /*打印错误输出*/ 9 void PrintError (std::string error); 10 /*string转换成int*/ 11 int StrToInt (const char *s); 12 13 void PrintError (std::string error) 14 { 15 std::cout << error <<", please input a right string" << std::endl; 16 exit (EXIT_FAILURE); 17 } 18 19 int StrToInt (const char *s) 20 { 21 //处理输入为NULL 22 if (NULL == s) 23 { 24 PrintError ("string is NULL"); 25 } 26 27 //忽略前面的空白符 28 while (isspace (*s)) 29 { 30 ++s; 31 } 32 33 //处理输入为负数或者带+的整数的情况 34 bool negFlag = false; 35 if ('-' == *s) 36 { 37 negFlag = true; 38 ++s; 39 } 40 else if ('+' == *s) 41 { 42 ++s; 43 } 44 45 //进行转换 46 long long result = 0; 47 long long temp = 0; 48 while ('\0' != *s) 49 { 50 //判断是否有小数点 51 if ('.' == *s) 52 { 53 break; 54 } 55 temp = *s - '0'; 56 if (0 > temp || 57 9 < temp) 58 { 59 PrintError ("string is wrong"); 60 } 61 result = result * 10 + temp; 62 if ((false == negFlag && INT_MAX < result) || 63 (true == negFlag && (INT_MIN > 0 - result)))//溢出 64 { 65 PrintError ("Overflowed"); 66 exit (EXIT_FAILURE); 67 } 68 ++s; 69 } 70 if ( true == negFlag) 71 { 72 result = 0 - result; 73 } 74 return result; 75 } 76 77 int main () 78 { 79 string s = "3333333.23"; 80 cout << StrToInt (s.c_str ()) << endl; 81 s = " +123"; 82 cout << StrToInt (s.c_str ()) << endl; 83 s = " -123.23"; 84 cout << StrToInt (s.c_str ()) << endl; 85 s = " 1234235353463465465467"; 86 cout << StrToInt (s.c_str ()) << endl; 87 return 0; 88 }
运行结果如下:
3333333 123 -123 Overflowed, please input a right string
浙公网安备 33010602011771号