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
  • 159
  • 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
  • 72,253
  • 8
  • 102
  • 198
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214