0

What is a good way to convert character array of varying sizes to a string? (C++)

Story: Hello, I tried to create a function in C++ that converts a character's integer value to a string, for example f('x') -> "120" and f('4') -> "52". I prefer modifying the string as an array of characters inside the function and then convert it to string before returning it, but... Actual problem: I somehow end up getting garbage values. The problem seems to caused by the conversion. I think it happens, because the char array-to-string conversion doesn't know the size of the character array, which can vary between 1, 2 and 3, making string assume the character array has 3 characters causing extra characters to be replaced with garbage values. I've tried to using string.resize function to cut off the garbage values, but I have a feeling it's not a good way. Questions: What are good ways to convert character array of varying sizes to a string? Is cutting garbage values off the string using string.resize function a good way to fix the problem? Is there a way to initialize a string with a specified length? Here is the code: https://code.sololearn.com/clHWHfZs5flZ

31st Mar 2022, 8:48 PM
Seb TheS
Seb TheS - avatar
3 ответов
+ 2
Ipang Thanks, maybe a good alternative to the whole function, but didn't really answer to my questions.
31st Mar 2022, 9:46 PM
Seb TheS
Seb TheS - avatar
+ 1
Perhaps std::to_string can help (don't forget to include <string>) string reprCharAsInt(unsigned char c) { return std::to_string( static_cast< int >( c ) ); }
31st Mar 2022, 9:05 PM
Ipang
+ 1
FF9900 Nice, thanks! That solved much confusion and misunderstanding about null-terminators. Thought null-terminators were only needed when printing character arrays, but seems like they are also needed in to-string conversions.
31st Mar 2022, 9:43 PM
Seb TheS
Seb TheS - avatar