C++使用技巧(二十三):回顾整形转化为字符串

其中有使用itoa(),atoi(),sprintf()这三个函数

使用字符串流

 1 #include<iostream>
 2 #include<string>
 3 #include<sstream>
 4 using namespace std;
 5 string itos(int i) // 将int 转换成string{
 6 {
 7     stringstream s;
 8 s << i;
 9 return s.str();
10  }
11  int main() {
12      int i = 127;
13      string ss = itos(i);
14      const char* p = ss.c_str();
15      cout << ss << " " << p << "\n";
16  }

参考:http://c.biancheng.net/view/208.html

itoa()函数

itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用的基数。在上例中,转换基数为10。10:十进制;2:二进制…

itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。
是Windows平台下扩展的,标准库中有sprintf,功能比这个更强,用法跟printf类似:


#include <iostream>
#include <numeric>
#include <iterator>
#include <vector>
#include <algorithm>

namespace ClassFoo

{
    void Iota_1() 
    {
        std::vector<int> foo;// 构造一个 vector 对象
        foo.resize(15);        
        std::iota(foo.begin(), foo.end(), 9);// 将从 9 开始的 15 次递增值赋值给 foo
        // 输出 foo 中的内容
        std::copy(foo.begin(),foo.end(),std::ostream_iterator<int>(std::cout, " "));
        std::cout << std::endl;
    }
}

int main()
{
    //案例1
    ClassFoo::Iota_1();   

    //案例2
    int a[20];
    std::iota(std::begin(a),std::end(a),1);//给数组赋值
    std::for_each(std::begin(a),std::end(a),[](int n){std::cout<<n<<" ";});
    
    // [](int n){std::cout<<n<<" ";};
    return 0;
}
//输出结果:
// 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 
// 1 2 3 4 5 6 7 8 9 10

其中:{}属于Lambda 的语法形式如下:

[函数对象参数] (操作符重载函数参数) mutable 或 exception 声明 -> 返回值类型 {函数体}

参考:https://docs.microsoft.com/en-us/cpp/cpp/lambda-expression170


案例1:

#include<iostream>
#include <unistd.h>
 #include<string>
 #include<sstream>

using namespace std;
string itos(int i) // 将int 转换成string{
    {
        stringstream s;
        s << i;
        return s.str();
}

int main() {

    string s1 = "num";
    
   
    int num = 0;
	while (num < 10)
	{
        string ss = itos(num);
        const char* p = ss.c_str();
		cout << s1+ss + "="  << num*2 << endl;
        cout << ss << " " << p << "\n";
		num++;
	}


	pause();

	return 0;
}

执行结果:

num0=0
num1=2
num2=4
num3=6
num4=8
num5=10
num6=12
num7=14
num8=16
num9=18

参考:https://blog.csdn.net/weixin_43055404/article/details/103299156

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源代码杀手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值