ROVguy
ROVguy

Reputation: 13

Using C++, Issue with converting int to char always having 3 digits

I'm trying to convert an integer with value of 1-360 and save it as a char of value 001-360. Examples 1 = 001, 43 = 043, 349 = 349. (If there's a better approach than char I'm all ears)

I've looked for different approaches weather using string or char[] but can't seem to get it right.

LOtrackAngle will be an int number 1-360

case 'q':
case 'Q':
{
    char trackAngleCHR[4];
    sprintf(trackAngleCHR, "%d", LOtrackAngle);
    ss << " 16"
       << "1" << trackAngleCHR << ""
       << "1"
       << "9";
    LOtrackAngle += 1;
    if (LOtrackAngle > 360)
    {
        LOtrackAngle = LOtrackAngle - 360;
    }
    break;
}

Is:

LOtrackAngle=248, Output is 16124819.
LOtrackAngle=34, Output is 1613419.
LOtrackAngle=7, Output is 161719.

Should be:

LOtrackAngle=7, Output is 16100719.

I need these to always be 8 characters long.

Upvotes: 1

Views: 542

Answers (3)

Yksisarvinen
Yksisarvinen

Reputation: 22324

Since you already use streams, I recommend to use fully C++ solutions:

#include <iomanip> //for std::setw

case 'q':
case 'Q':
{
    ss << " 16" << "1" 
       << std::setw(3) << std::setfill('0') << LOtrackAngle
       << "1" << "9";

    LOtrackAngle += 1;
    if (LOtrackAngle > 360)
    {
        LOtrackAngle = LOtrackAngle - 360;
    }
    break;
}

It is not only more concise and easier to read, but also safe against buffer overflow (in case your number won't fit in buffer of length 4 for some reason, you won't get some strange UB)

Upvotes: 4

PaulMcKenzie
PaulMcKenzie

Reputation: 35454

Here is an alternative that doesn't use extra strings or streams.

#include <cstring>
#include <iostream>

char* fill_char_array(char *arr, int size, int num)
{
    if ( size <= 0 )
       return arr;
    memset(arr, '0', size);  // set all positions to character 0
    arr[size-1] = 0;  // null terminate
    int index = size - 2;
    while (num > 0 && index >= 0)
    {
       arr[index] = (num % 10) + '0';  // set the digit in the array
       num /= 10;
       --index;
    }
    return arr;
}

int main()
{
    char trackAngleCHR[4];
    std::cout << fill_char_array(trackAngleCHR, 4, 38) << "\n";
    std::cout << fill_char_array(trackAngleCHR, 4, 1) << "\n";
    std::cout << fill_char_array(trackAngleCHR, 4, 534) << "\n";
}

Output:

038
001
534

Upvotes: 0

Alex Hodges
Alex Hodges

Reputation: 607

Take a look at this:

int main()
{
    int number = 360;
    char chars[4];
    auto str = std::to_string(number);
    str.insert(0, 3 - str.size(), '0');
    std::memcpy(chars,str.data(),str.size());

    return 0;
}

Using this method you could either keep the original string, or memcpy it to a char[].

EDIT: Added one liner to insert 0's if needed.

Upvotes: 0

Related Questions