0

Please tell me how to convert int to char in c++ style? The content in str1 is "\001", while the content in str2 is "1"; Can I use static_cast to get the same result as str2?
The code is as follows:

#include <iostream>

using namespace std;

int main()
{
    int a = 1;
    string str1;
    string str2;

    str1.push_back(static_cast<char>(a));
    str2.push_back('0' + a);
    cout << str1 << str2;

    return 0;
}
fizzbuzz
  • 113
  • 1
  • 1
  • 8

1 Answers1

1

It depends on the exact use-case. For a direct int-to-string conversion, use std::to_string.

When streaming the output, there are usually better options, including using fmt (part of C++20, available as a separate library before that).

Olaf Dietsche
  • 69,448
  • 7
  • 95
  • 188
Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183