在C ++ STL中使用string :: to_string()将数字转换为字符串

to_string() is a library function of <string> header, it is used to convert numeric value (number) to string.

to_string()是<string>标头的库函数,用于将数值(数字)转换为字符串。

Syntax:

句法:

string to_string(numberic_value);

Here,

这里,

  • string is the return type i.e. function returns an string object that contains the numeric value in string format.

    string是返回类型,即函数返回一个字符串对象,其中包含字符串格式的数字值。

  • numbric_value is the number which can be integer, float, long, double.

    numbric_value是可以为整数,浮点数,长整数,双精度数的数字。

Example:

例:

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

int main ()
{
	//definition of different types of data type
	int intVal =12345;
	float floatVal = 123.45f;
	long longVal = 123456789;

	//converting values to string an printing
	cout<<"intVal (string format) : "<<to_string (intVal) <<endl;
	cout<<"floatVal (string format) : "<<to_string (floatVal) <<endl;
	cout<<"floatVal (string format) : "<<to_string (longVal) <<endl;

	return 0;
}

Output

输出量

    intVal (string format) : 12345
    floatVal (string format) : 123.449997
    floatVal (string format) : 123456789


Expressions results can also be converted to string directly (as the type of expression’s result is numeric)

表达式结果也可以直接转换为字符串(因为表达式结果的类型是数字)

Consider the example:

考虑示例:

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

int main ()
{
	cout<<to_string (10+20+30+40) <<endl;
	cout<<to_string (10+20+12.34) <<endl;
	cout<<to_string (10/20+30*2) <<endl;

	return 0;
}

Output

输出量

    100
    42.340000
    60

不使用“使用命名空间std”的函数和对象 (Functions and object without using 'using namespace std')

using namespace std is an statement that tells to the compiler to use namespace named std, if we do not write this statement, then we need to use std:: with all functions, objects.

using namespace std是一条语句,告诉编译器使用名为std的命名空间,如果我们不编写此语句,则需要对所有函数,对象使用std :: 。

Consider the example:

考虑示例:

#include <iostream>
#include <string>

int main ()
{
	std::cout<<std::to_string (10+20+30+40) <<std::endl;
	std::cout<<std::to_string (10+20+12.34) <<std::endl;
	std::cout<<std::to_string (10/20+30*2) <<std::endl;

	return 0;
}

Output

输出量

    100
    42.340000
    60


翻译自: https://www.includehelp.com/stl/convert-numeric-to-string-using-string-to-string.aspx

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值