In this blog we will learn different way of Converting numbers to strings in C++ and C++11. This type of conversion is very recurring problem. Most of the time developers face this problem.

Converting numbers to strings in C++

  • C++¬† stringstreams ( this method also works in c++ 11)
#include <iostream>
#include <sstream>

std::string num_to_str(int num) {
	std::ostringstream sobj;
	sobj << num;
	return sobj.str();
}

int main() {
	std::cout << num_to_str(1234) <<std::endl;
	return 0;
}
  • Using c++ 11 std::to_string
#include <iostream>

int main() {
	std::cout << std::to_string(1234) <<std::endl;
	return 0;
}
  • C++ 11 std::to_string¬† can also convert floating point numbers into strings
#include <iostream>

int main() {
	std::cout << std::to_string(1234.40) <<std::endl;
	return 0;
}

Ref:

http://www.cplusplus.com/articles/D9j2Nwbp/



Related Contents to follow