急:字符串如何转换为整数,如"12345"(是字符串)转换为12345
解析一下原理!不要代码!
[ 本帖最后由 huangqing 于 2009-11-12 19:04 编辑 ]
#include <iostream> #include <cstring> #include <cmath> using namespace std; int SToI(const char*& str) { int var = 0; int len = 0; len = strlen(str); char c; for(int i=0; i<len; ++i) { c=str[i]; var = var*10 + (int)(c-48); } return var; } int main() { const char* str = "12345"; int var = SToI(str); cout << "\"" << str << "\" = " << var << endl; return 0; }
#include <iostream> #include <cstring> #include <cmath> using namespace std; int SToI(const char*& str) { int var = 0; int len = 0; len = strlen(str); char c; for(int i=0; i<len; ++i) { c=str[i]; var = var*10 + (int)(c-48); } return var; } int main() { const char* str = "12345"; int var = SToI(str); cout << "\"" << str << "\" TO " << var << endl; return 0; }
#include <iostream> #include <sstream> #include <cstdlib> #include <cstdio> using namespace std; int main() { char *str = "12345"; long n; n = strtol(str, NULL, 10); cout<<"using strtol(), n = "<<n<<endl; n = strtoul(str, NULL, 10); cout<<"using strtoul(), n = "<<n<<endl; sscanf(str, "%ld", &n); cout<<"using sscanf(), n = "<<n<<endl; stringstream sin; sin<<str; sin>>n; cout<<"using stringstream, n = "<<n<<endl; return 0; }