几种c/c++中字符串转整形的方法

本文介绍了六种将字符串转换为数值的方法:自定义函数、使用atoi/atof/atol、sscanf、strtol/strtod、istringstream及boost lexical_cast。每种方法都提供了详细的代码示例,帮助读者理解和应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. using namespace 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. using namespace 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++)

可以到www.boost.org下载最新的boost库,设置IDE的include路径就可以使用大部分boost功能了,具体可以参考http://www.stlchina.org/twiki/bin/view.pl/Main/BoostChina

  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. }

    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. using namespace 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. using namespace 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++)

    可以到www.boost.org下载最新的boost库,设置IDE的include路径就可以使用大部分boost功能了,具体可以参考http://www.stlchina.org/twiki/bin/view.pl/Main/BoostChina

    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. }
    17. http://blog.youkuaiyun.com/alien73/article/details/3477033
### C++字符串整型的方法C++ 编程中,将字符串换为整型是一种常见需求。以下是几种常用方法及其特点: #### 使用 `atoi` 函数 `atoi` 是标准库 `<cstdlib>` 提供的一个简单函数,用于将 C 风格字符串(即以 `\0` 结尾的字符数组)换为整数[^2]。 其语法如下: ```cpp #include <cstdlib> int atoi(const char* str); ``` 此函数适用于简单的字符串到整数的换,但如果输入字符串包含非法字符或为空,则可能导致未定义行为。 示例代码: ```cpp #include <iostream> #include <cstdlib> using namespace std; int main() { const char* str = "123"; int result = atoi(str); cout << "Result: " << result << endl; return 0; } ``` --- #### 使用 `std::stoi` 函数 `std::stoi` 是 C++11 引入的标准库函数,位于头文件 `<string>` 中。相比 `atoi`,它提供了更强的安全性和灵活性[^3]。如果字符串中含有非数字字符,`std::stoi` 将抛出 `std::invalid_argument` 或 `std::out_of_range` 异常。 语法如下: ```cpp #include <string> int stoi(const string& str, size_t* pos = nullptr, int base = 10); ``` 参数说明: - `str`: 输入的字符串。 - `pos`: 如果提供,存储第一个无法被解释为整数的位置索引。 - `base`: 数字系统的基数,默认为十进制。 示例代码: ```cpp #include <iostream> #include <string> using namespace std; int main() { try { string str = "123abc"; int result = stoi(str); cout << "Result: " << result << endl; } catch (const invalid_argument& e) { cerr << "Invalid argument: " << e.what() << endl; } catch (const out_of_range& e) { cerr << "Out of range: " << e.what() << endl; } return 0; } ``` --- #### 手动实现字符串整型逻辑 当需要更高的控制度时,可以手动编写字符串整型的逻辑。这种方法通常涉及遍历字符串中的每一位字符,并将其逐步累加至最终结果[^5]。 示例代码: ```cpp #include <iostream> #include <cstring> #include <cstdio> using namespace std; int stoii(const char a[]) { int len = strlen(a), num = 0, first; if (a[0] == '-') { first = 1; // 负号标志位 } else { first = 0; } for (int i = first; i < len; ++i) { if (!isdigit(a[i])) break; // 若遇到非数字字符则停止 num *= 10; num += (a[i] - '0'); } if (first) num *= -1; // 添加负号 return num; } int main() { char a[100]; cin.getline(a, sizeof(a)); cout << "Result: " << stoii(a) << endl; return 0; } ``` --- #### 使用流提取器 (`std::istringstream`) 另一种方式是利用输入字符串流对象 `std::istringstream` 来完成字符串到整型的换[^4]。这种方式的优点在于能够轻松处理复杂的格式化数据。 示例代码: ```cpp #include <iostream> #include <sstream> using namespace std; int StringToInt(const string& str) { int ret; stringstream ss(str); ss >> ret; return ret; } int main() { string str = "456"; cout << "Result: " << StringToInt(str) << endl; return 0; } ``` --- ### 各方法对比总结 | 方法 | 易用性 | 安全性 | 支持范围 | |--------------|-------------|--------------------|-------------------| | `atoi` | 简单易用 | 较低 | 基本整数 | | `std::stoi` | 较高 | 高 | 自定义基底支持 | | 手动实现 | 复杂 | 受控于开发者 | 灵活可扩展 | | 流提取器 | 中等 | 中等 | 格式化数据友好 | 推荐优先使用 `std::stoi`,因为它既安全又灵活,同时兼容现代 C++ 的最佳实践。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值