How to convert int to char array in C++

3 Answers

0 votes
#include <iostream>

int main() {
    int n = 1234;

    std::string s = std::to_string(n);
    char const *arr = s.c_str();
    
    for (int i = 0; arr[i]; i++)
        std::cout << arr[i] << " ";
 
    return 0;
}
 
 
 
 
/*
run:
 
1 2 3 4 
 
*/

 



answered May 16, 2021 by avibootz
0 votes
#include <iostream>
#include <sstream>

int main() {
    int n = 1234;

    std::stringstream s;
    s << n;

    char const *arr = s.str().c_str();
    
    for (int i = 0; arr[i]; i++)
        std::cout << arr[i] << " ";
 
    return 0;
}
 
 
 
 
/*
run:
 
1 2 3 4 
 
*/

 



answered May 16, 2021 by avibootz
0 votes
#include <iostream>
#include <charconv>

int main() {
    int n = 1234;
    char arr[10] = "";

    std::to_chars(arr, arr + 10, n);
    
    for (int i = 0; arr[i]; i++)
        std::cout << arr[i] << " ";
 
    return 0;
}
 
 
 
 
/*
run:
 
1 2 3 4 
 
*/

 



answered May 16, 2021 by avibootz

Related questions

1 answer 171 views
1 answer 131 views
131 views asked Sep 20, 2021 by avibootz
1 answer 194 views
1 answer 199 views
199 views asked Feb 28, 2021 by avibootz
1 answer 273 views
273 views asked Jun 13, 2017 by avibootz
2 answers 229 views
229 views asked Apr 2, 2017 by avibootz
1 answer 190 views
...