How to Convert an int or float to String

beginner c++11 strings

Related: string to int or float

The C++ standard library provides the std::to_string function for converting numbers to strings. This works for integer numbers as well as floating point numbers however there is no way to set the pecision of floating point numbers with std::to_string. Here’s an example:

#include <string>
#include <iostream>

int main() {
  int i = -100;
  std::string s = std::to_string(i);
  std::cout << s << "\n";

  // We'll lose some precision here
  float pi = 3.145926535; 
  std::string s2 = std::to_string(pi);
  std::cout << s2 << "\n";

For more C++ By Example, click here.