1. 程式人生 > >幾種c/c++中字串轉整形的方法

幾種c/c++中字串轉整形的方法

1.自己寫一個函式(c/c++)

  1. #include <stdio.h>
  2. #include <assert.h>
  3. /*  my string to integer function  */
  4. int myfun(char *str){
  5. int i = 0,n = 0,flag = 1;
  6. if(str[0] == '-')
  7.         i = 1;flag = -1;
  8. for(; str[i] != '/0' ; i++){
  9.         assert(str[i] >= '0' && str[i] <= '9');
  10.         n = str[i] - 
    '0' + n*10;
  11.     }
  12. return n*flag;
  13. }
  14. int main(int argc, char *argv[])
  15. {
  16. int a;
  17. char str[] = "1024";
  18.     a = myfun(str);
  19.     printf("%d/n",a);
  20. return 0;
  21. }

2.使用c標準庫中的atoi函式(c/c++)

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main(int argc, char *argv[])
  4. {
  5. int a;double d;
  6. char str[] = "1024";
  7. char strd[] = 
    "3.1415";
  8.     a = atoi(str);d =atof(strd);
  9.     printf("%d/n",a);
  10.     printf("%g/n",d);
  11. return 0;
  12. }
  1. #include <iostream>
  2. #include <string>
  3. usingnamespace std;
  4. int main(int argc, char *argv[])
  5. {
  6. int a;
  7.     string str = "1024";
  8.     a = atoi(str.c_str());
  9.     cout << a <<endl;
  10. return
     0;
  11. }

其他相關函式還有atof,atol等。

3.使用sscanf函式(c/c++)

  1. #include <stdio.h>
  2. int main(int argc, char *argv[])
  3. {
  4. int a;double d;
  5. char str[] = "1024";
  6. char strd[] = "3.1415";
  7.     sscanf(str,"%d",&a);
  8.     sscanf(strd,"%lf",&d);
  9.     printf("%d/n",a);
  10.     printf("%g/n",d);
  11. return 0;
  12. }

4.使用c標準庫中的strtol函式(c/c++)

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main(int argc, char *argv[])
  4. {
  5. int a,hex_a;double d;
  6. char str[] = "1024";
  7. char hex_str[] = "ff";
  8. char strd[] = "3.1415";
  9.     a = strtol(str,NULL,10);hex_a = strtol(hex_str,NULL,16);
  10.     d =strtod(strd,NULL);
  11.     printf("%d/n",a);
  12.     printf("%d/n",hex_a);
  13.     printf("%g/n",d);
  14. return 0;
  15. }

其他相關函式還有strtoul,將字串轉換成無符號的長整型數。

5.使用c++中的字串流istringstream(c++)

  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. usingnamespace std;
  5. int main(int argc, char *argv[])
  6. {
  7. int a;
  8.     string str = "-1024";
  9.     istringstream issInt(str);
  10.     issInt >> a;
  11.     cout << a <<endl;
  12. return 0;
  13. }

不過,GCC(2.95.2)及以前版本並不支援sstream。

6.使用boost庫中的lexical_cast函式(c++)

  1. #include <boost/lexical_cast.hpp>
  2. #include <iostream>
  3. int main()
  4. {
  5. using boost::lexical_cast;
  6. try{
  7. int a = lexical_cast<int>("1024");
  8. //int a = lexical_cast<int>("xxx"); // exception
  9. double d = lexical_cast<double>("3.14194");
  10.     std::cout<<a<<std::endl;
  11.     std::cout<<d<<std::endl;
  12.     }catch(boost::bad_lexical_cast& e){
  13.         std::cout<<e.what()<<std::endl;
  14.     }
  15. return 0;
  16. }