(im still learning c++ and wanted to try and make my own Int to String function, so apologies if what ive done doesn't fit any standards...)
i made this function to convert ints to a string (well, a const char*), this is the code here:
#include <iostream>
#include <vector>
char IntToChar(int value) {
if (value < 0 || value > 9) {
return '0';
}
return (char)(value + 48);
}
const char* IntToString(int value) {
char buffer[11];
memset(&buffer, 0, sizeof(buffer));
std::vector<int> splitValue;
while (true) {
splitValue.insert(splitValue.begin(), value % 10);
value /= 10;
if (value == 0)
break;
}
for (int i = 0; i < splitValue.size(); i++) {
buffer[i] = IntToChar(splitValue[i]);
}
splitValue.clear();
return buffer;
}
int main()
{
int value = 123789;
const char* valueString = IntToString(value);
std::cout << valueString << '\n';
}
but when i write valueString to cout (the console), the number is nowhere to be seen; it's just random characters. i debugged the entire function and found it successfully turned the numbers into chars and returned those chars in an array. what could be going wrong here? i assume it's because it returns an array who's length is 11 but only a few elements are filled (for a small number). but i could be wrong
edit: issue was that the buffer was getting killed just as the function ends due to it being a pointer (i assume). so i replaced const char* with std::string, and where i actually added the code to the buffer, instead of buffer[i], i did buffer +=.