从 int 到 string 的几种方法(C++)

本文详细介绍了C++中将整数转换为字符串的四种方法:使用`printf`函数、`itoa`函数、`stringstream`类和自定义函数。包括代码示例和输出结果分析。

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

参考链接:http://www.cppblog.com/forLinda/archive/2006/03/17/4298.html

法一

/**
 * <stdio.h>
 * int sprintf( char *buffer, const char *format [, argument] ... );
 */
void int2str0() {
    int ss;
    char temp[64];
    string str;
    ss = 87676990;
    sprintf(temp, "%d", ss);
    string s(temp);
    cout << s.c_str() << endl;  // 87676990
    cout << s.size() << endl;   // 8
}

法二

/**
 * <stdlib.h>
 * char *_itoa( int value, char *string, int radix );
 */
void int2str1() {
    char buf[20];
    int i = 3445;
    _itoa(i, buf, 10);
    string s(buf);
}

法三

/**
 * <sstream.h> or <sstream>
 */
void int2str2() {
    int hello = 4;
    stringstream ss;
    ss << hello;
    string s = ss.str();
    cout << s.c_str() << endl;
}

法四

string int2str(int num) {
    string str = "";
    if (num == 0) {
        return "0";
    }
    
    bool bNegative = (num < 0);
    
    num = abs(num);
    while (num) {
        str = (char)(num % 10 + 48) + str ;
        num /= 10; 
    } 
    return bNegative ? "-" + str : str;
}

### C++ 中字符串与整数相互转换 #### 字符串转整数 (`string` 到 `int`) 在现代 C++ 编程中,可以使用标准库中的多种方式来进行字符串到整数的转换。 一种常用的方式是利用 `<cstdlib>` 头文件提供的 `std::stoi()` 函数: ```cpp #include <iostream> #include <string> try { std::string s = "123"; int num = std::stoi(s); } catch (const std::invalid_argument& e) { // Handle invalid argument exception } ``` 另一种方法则是通过自定义实现,例如借助于字符处理函数逐位解析数字[^1]。不过这种方式较为复杂且容易出错,在实际开发中不推荐直接这样做;而是应该优先考虑使用现成的标准库接口。 对于更复杂的场景下可能还需要考虑到不同进制之间的转换等问题,则可选用其他相应版本如 `std::stol`, `std::stoul` 或者 `std::sscanf` 来完成任务[^3]。 #### 整数转字符串 (`int` 到 `string`) 同样地,当涉及到将整数值转化为其对应的字符串表示形式时,也有几种不同的途径可以选择。 最简单直观的办法就是调用 `<sstream>` 提供的 `std::to_string()` 方法: ```cpp #include <iostream> #include <string> int main() { int value = 456; std::string result = std::to_string(value); return 0; } ``` 此操作会自动根据传入的数据类型选择合适的内部逻辑进行格式化输出。 另外还可以采用流式输入/输出机制配合 ostringstream 类型对象达成相同效果: ```cpp #include <sstream> #include <string> std::ostringstream oss; oss << numberValue; std::string stringValue = oss.str(); ``` 上述两种方案均能有效满足日常编程需求,并具有良好的跨平台兼容性和稳定性特点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值