下面代码仅供本人复习所用,实用性N低,各位飘过吧~~哈哈:>
// // 字符串转换为整数. // #include <cstdlib> #include <iostream> #include <string> long toInteger(const std::string &str) { bool isNegative = false; long result = 0; size_t i; const size_t length = str.length(); // // 跳过非数字或符号的字符. // for (i = 0; i < length && ('0' > str[i] || '9' < str[i]); ++i) { // // 处理负号. // if ('-' == str[i] && '0' <= str[i + 1] && '9' >= str[i + 1]) { isNegative = true; i++; break; } } // // 处理数字. // while (i < length && '0' <= str[i] && '9' >= str[i]) { result = 10 * result + (str[i++] - '0'); } return true == isNegative ? result * -1 : result; } int main(void) { std::cout << toInteger("123456") << std::endl; std::cout << toInteger("-123456") << std::endl; std::cout << toInteger("--123456-") << std::endl; std::cout << toInteger("abBsD-123456") << std::endl; std::cout << toInteger("abBsD-123456XddeE") << std::endl; std::cout << toInteger("abBsD123456XddeE") << std::endl; return EXIT_SUCCESS; }