C++ int converted to string

We can use C standard library or C++ library functions/classes to convert int to string.

The "modern" C++ style approach

We can use std::to_string() in the C++ standard library, which has been added to the C++ standard library since 11 years. If the project uses C++ 11 and later standards, this method is recommended.

std::string to_string( int value );

Defined in the standard header to convert the value to std::string.
1) It has the same function as std::sprintf (buf, "%d", value), which converts a signed decimal integer into a character string.

An example of a program for C++ is as follows.

std::to_string()

#include <iostream>
#include <string>

int main ()
{
    
    
  int n = 123;
  std::string str = std::to_string(n);
  std::cout << n << " ==> " << str << std::endl;

  return 0;
}

Note that exceptions may be thrown from the constructor. If the caller intends to handle this exception, the caller may need to catch the following exception.

std::to_string() std::bad_allocstd::string

Based on C++ style stream

We can use the C++ library std::stringstream, which has been used before C++11 to convert int to string. The one using C++ program is as follows.

std::stringstream

#include <sstream>
#include <iostream>

int main()
{
    
    
  int i = 123;
  std::stringstream ss;
  ss << i;
  std::string out_string = ss.str();
  std::cout << out_string << "\n";
  return 0;
}

C style method

We can also use C standard C++ functions in the application. A C standard library function, snprintf() that can perform int to string conversion.

#include <stdio.h>

int snprintf(char *str, size_t size, const char *format, ...);

The functions snprintf() and vsnprintf() write at most size bytes (including the terminating null byte ('\0')) to str.

The following is an example of using functions to convert int to string in C++.

snprintf()

#include <cstdio>
#include <iostream>

#define MAX_BUFFER_SIZE 128

int main()
{
    
    
  int number = 123;
  char out_string [MAX_BUFFER_SIZE];
  int rt = snprintf(out_string, MAX_BUFFER_SIZE, "%d", number);
  if (rt < 0) {
    
    
    std::cerr << "snprintf() failed with return code " << rt << std::endl;
  } else {
    
    
    std::cout << "out_string = \"" << out_string << "\"\n";
  }
  return 0;
}

Reference materials:
https://www.systutorials.com/how-to-convert-int-to-string-in-cpp/

Guess you like

Origin blog.csdn.net/yao_zhuang/article/details/112450802