幾種c/c++中字串轉整形的方法
阿新 • • 發佈:2019-02-01
1.自己寫一個函式(c/c++)
- #include <stdio.h>
- #include <assert.h>
- /* my string to integer function */
- int myfun(char *str){
- int i = 0,n = 0,flag = 1;
- if(str[0] == '-')
- i = 1;flag = -1;
- for(; str[i] != '/0' ; i++){
- assert(str[i] >= '0' && str[i] <= '9');
- n = str[i] -
- }
- return n*flag;
- }
- int main(int argc, char *argv[])
- {
- int a;
- char str[] = "1024";
- a = myfun(str);
- printf("%d/n",a);
- return 0;
- }
2.使用c標準庫中的atoi函式(c/c++)
- #include <stdio.h>
- #include <stdlib.h>
- int main(int argc, char *argv[])
- {
- int a;double d;
- char str[] = "1024";
- char strd[] =
- a = atoi(str);d =atof(strd);
- printf("%d/n",a);
- printf("%g/n",d);
- return 0;
- }
- #include <iostream>
- #include <string>
- usingnamespace std;
- int main(int argc, char *argv[])
- {
- int a;
- string str = "1024";
- a = atoi(str.c_str());
- cout << a <<endl;
- return
- }
其他相關函式還有atof,atol等。
3.使用sscanf函式(c/c++)
- #include <stdio.h>
- int main(int argc, char *argv[])
- {
- int a;double d;
- char str[] = "1024";
- char strd[] = "3.1415";
- sscanf(str,"%d",&a);
- sscanf(strd,"%lf",&d);
- printf("%d/n",a);
- printf("%g/n",d);
- return 0;
- }
4.使用c標準庫中的strtol函式(c/c++)
- #include <stdio.h>
- #include <stdlib.h>
- int main(int argc, char *argv[])
- {
- int a,hex_a;double d;
- char str[] = "1024";
- char hex_str[] = "ff";
- char strd[] = "3.1415";
- a = strtol(str,NULL,10);hex_a = strtol(hex_str,NULL,16);
- d =strtod(strd,NULL);
- printf("%d/n",a);
- printf("%d/n",hex_a);
- printf("%g/n",d);
- return 0;
- }
其他相關函式還有strtoul,將字串轉換成無符號的長整型數。
5.使用c++中的字串流istringstream(c++)
- #include <iostream>
- #include <string>
- #include <sstream>
- usingnamespace std;
- int main(int argc, char *argv[])
- {
- int a;
- string str = "-1024";
- istringstream issInt(str);
- issInt >> a;
- cout << a <<endl;
- return 0;
- }
不過,GCC(2.95.2)及以前版本並不支援sstream。
6.使用boost庫中的lexical_cast函式(c++)
- #include <boost/lexical_cast.hpp>
- #include <iostream>
- int main()
- {
- using boost::lexical_cast;
- try{
- int a = lexical_cast<int>("1024");
- //int a = lexical_cast<int>("xxx"); // exception
- double d = lexical_cast<double>("3.14194");
- std::cout<<a<<std::endl;
- std::cout<<d<<std::endl;
- }catch(boost::bad_lexical_cast& e){
- std::cout<<e.what()<<std::endl;
- }
- return 0;
- }