【C++】int转string

c++11 新增函数:std::to_string()

头文件:#include<string>

#include <string> 
using namespace std;
int main(){
    int n=100;
    string str=to_string(n);
    return 0;
}

对int 判断单个位数数字

可以利用除法+判断余数形式!!

	while (num)
	{
		if (num % 10 == 7) return true;
		else num /= 10;
	}
### C++中将int类型换为string类型的方法 在C++中,可以使用多种方法将`int`类型换为`string`类型。以下是几种常见的实现方式: #### 1. 使用 `std::to_string` `std::to_string` 是 C++11 引入的一个简单且高效的方法,可以直接将整数换为字符串[^2]。 ```cpp #include <iostream> #include <string> int main() { int number = 12345; std::string str = std::to_string(number); std::cout << "Converted string: " << str << std::endl; return 0; } ``` #### 2. 使用 `std::stringstream` 通过 `std::stringstream`,可以将整数插入到流中,并从流中提取字符串[^4]。 ```cpp #include <iostream> #include <sstream> #include <string> int main() { int number = 12345; std::stringstream ss; ss << number; std::string str = ss.str(); std::cout << "Converted string: " << str << std::endl; return 0; } ``` #### 3. 使用 `sprintf` `sprintf` 是一个传统的 C 风格函数,可以将整数格式化为字符串并存储在字符数组中[^4]。 ```cpp #include <iostream> #include <cstdio> #include <string> int main() { int number = 12345; char buffer[20]; sprintf(buffer, "%d", number); std::string str = buffer; std::cout << "Converted string: " << str << std::endl; return 0; } ``` #### 4. 使用 `itoa`(非标准方法) `itoa` 是 Windows 平台特有的非标准函数,可以将整数换为字符串。需要注意的是,该方法不具备跨平台特性。 ```cpp #include <iostream> #include <cstdlib> #include <string> int main() { int number = 12345; char buffer[20]; itoa(number, buffer, 10); std::string str = buffer; std::cout << "Converted string: " << str << std::endl; return 0; } ``` #### 5. 自定义实现 如果需要手动实现换逻辑,可以通过逐位提取数字并构造字符串来完成[^5]。 ```cpp #include <iostream> #include <string> std::string to_String(int n) { int m = n; char s[100]; char ss[100]; int i = 0, j = 0; if (n < 0) { m = 0 - m; j = 1; ss[0] = '-'; } while (m > 0) { s[i++] = m % 10 + '0'; m /= 10; } s[i] = '\0'; i = i - 1; while (i >= 0) { ss[j++] = s[i--]; } ss[j] = '\0'; return ss; } int main() { int number = -12345; std::string str = to_String(number); std::cout << "Converted string: " << str << std::endl; return 0; } ``` ### 注意事项 - 推荐优先使用 `std::to_string`,因为它简单、易用且具备跨平台支持。 - 如果需要兼容旧版本的 C++ 编译器,可以选择 `std::stringstream` 或 `sprintf`。 - 对于跨平台开发,避免使用 `itoa`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值