【Cpp 语言基础】C++的to_string()函数和C语言中的itoa()函数的使用

C++的to_string()函数

头文件 :#include<string>

功能:将数字常量转换为字符串。相当于C语言中的itoa()函数

参数:value

返回值:转换好的字符串

重载版本:

整数类型:

  • std::string to_string(int/long/long long value); 
  • std::string to_string(unsigned/unsigned long/unsigned long long value);

浮点类型:

  • std::string to_string(float value); 
  • std::string to_string(double value); 
  • std::string to_string(long double value); 

举例:

#include <iostream>   // std::cout
#include <string>     // std::string, std::to_string
using namespace std ;
 
int main()
{
	std::string pi = "pi is " + std::to_string(3.1415926);
	std::string perfect = std::to_string(1 + 2 + 4 + 7 + 14) + " this is a perfect number";
	std::cout << pi << '\n';
	std::cout << perfect << '\n';
	
	system("pause");
 
 
}

常见的应用场合:IP地址的转换

#include <iostream>
#include <string>
using namespace std;

unsigned long int ip_to_int(string ip) {
    unsigned long int num = 0;
    int i = 0;
    while (i < ip.size()) {
        if (ip[i] == '.') {
            num = (num << 8) + stoi(ip.substr(i - 3, 3));
        }
        i++;
    }
    num = (num << 8) + stoi(ip(i - 3, 3));
    return num;
}

string int_to_ip(unsigned long int num) {
    string ip = "";
    for (int i = 0; i < 4; i++) {
        ip = to_string(num % 256) + "." + ip;//此处应用了 to_string() 函数。
        num /= 256;
    }
    ip.pop_back();
    return ip;
}

int main() {
    string ip = "192.168.0.1";
    unsigned long int num = ip_to_int(ip);
    cout << "ip = " << ip << endl;
    cout << "num = " << num << endl;
    cout << "ip = " << int_to_ip(num) << endl;
    0;
}

 

C中的itoa()函数以及sprintf()函数

C语言一般用 sprintf() 函数实现数字到字符串的转变,用atoi()实现字符串到数字的转变。

itoa并非是一个标准的C/C++函数,它是Windows持有的,如果要写跨平台的程序,请用sprintf。

char *itoa (int value, char *str, int base );

功能:将整型的数字变量转换为字符数组变量。

int value 被转换的整数,char *string 转换后储存的字符数组,int radix 转换进制数,如2,8,10,16 进制等,大小应在2-36之间。

返回值:返回指向str的指针,无错误返回。

#include <stdlib.h>//cstdlib和stdlib.h都可以
#include <stdio.h>//cstdio和stdio.h都可以
//如果用的是cstdio和cstdlib,要加上 using namespace std;
int main(void)
{
    int number = 123456;
    char string[25];
    itoa(number, string,1 0);
    printf("integer=%d string=%s\n", number, string);
    return 0;
}
这个其实是C/C++非标准库中的函数,而是Windows平台下扩展的,标准库中有sprintf(注意是标准库),功能比这个强的多的啦,用法跟printf有点神似:
char str[255] = {0};

sprintf(str,"%d",100); //将100转为10进制表示的字符串。
sprintf(str,"%x",100); //将100转为16进制表示的字符串。
sprintf(str,"%o",100); //将100转为8进制表示的字符串。

 

参考文章:
1. https://blog.csdn.net/qq_18815817/article/details/82431685

2. https://baike.baidu.com/item/itoa/4747365?fr=ge_ala

 

posted @ 2023-12-11 11:56  FBshark  阅读(381)  评论(0编辑  收藏  举报