std::vector<int> int_vector = {1, 2, -2};
std::vector<char*> char_vector(int_vector.size());
for (size_t i = 0; i < int_vector.size(); ++i) {
char_vector[i] = new char[20]; // a reasonable size for each converted string
sprintf_s(char_vector[i], 20, "%d", int_vector[i]);
}
// char_vector contains the converted strings
for (const char* str : char_vector) {
std::cout << str << " ";
}
// free the allocated memory
for (char* str : char_vector) {
delete[] str;
}
#Transform int* into char*
42 messages Β· Page 1 of 1 (latest)
Here, a vector of datatype is converted into strings, and then stacked in string vector
Elaborate
Look at the beginning of the code
Just change that depending on what numbers you need
Yep π
Do you mean you want to cast an int vector into a char vector ?
Like
{1,5,-2} -> {β1β, β5β, β-2β}
Wait be right back
Are you french?
Ah alright, because we would communicate better if we spoke the same language natively
Anyways
Is this the plan?
Ohh you mean one string containing all the numbers?
Not familiar with string library in C++ but i can do that in C
And ye
In C is better than C++
Lets be honest C++ sometimes look messy
Dont worry, almost every C code is valid C++ code π
Im on phone right now
Please wait
@shadow trout
like this ?
the output is on the right side
Lemme rewrite in C++ then use sprintf_s
#include <iostream>
#include <cstdio>
#include <vector>
int main() {
std::vector<int> int_vector = {1, 2, -2};
std::vector<char> char_array;
for (int i = 0; i < int_vector.size(); ++i) {
char temp[20];
sprintf_s(temp, 20, "%d", int_vector[i]);
for (int j = 0; temp[j] != '\0'; ++j) {
char_array.push_back(temp[j]);
}
if (i < int_vector.size() - 1) {
char_array.push_back(' ');
}
}
std::cout << char_array.data() << std::endl;
return 0;
} ```
I gotta go
sprintf in c++ π
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
template<typename T>
std::string to_string(std::vector<T> const& v){
std::stringstream ss {};
for(T const& e : v){
ss << e << ' ';
}
std::string s {ss.str()};
s.resize(s.size() - 1);
return s;
}
int main(){
std::vector<int> arr {1, 2, 3};
std::cout << to_string(arr) << '\n';
return 0;
}
gcc main**.c** -o main
look down, on the left side
this is c++
it does not contain sprintf
.
.