Home » C++ STL

Convert numeric to string using string::to_string() in C++ STL



C++ STL: string::to_string() function with Example: In this tutorial, we will learn to convert numeric values to the string using to_string() function.
Submitted by IncludeHelp, on July 02, 2018

to_string() is a library function of <string> header, it is used to convert numeric value (number) to 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.
  • numbric_value is the number which can be integer, float, long, double.

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

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.

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





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.



Comments and Discussions





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.