0

The string str_hex contains the hex-values for the letters A-J, which corresponds to the decimal values 65-74. I'm trying to cast each hex-value to its decimal value following this example. It works nice for the std::cout case inside the for-loop, but the output-std::string still has the ascii-values. Why does this not work or is there a nicer/more proper way to build my output string?

#include <string>
#include <iostream>
#include <stdint.h>

int main()
{

    std::string str_hex("\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b", 10);
    std::string str_output = "";

    for (int i = 0; i < 10; ++i)
    {
        uint8_t tmp = str_hex[i];
        str_output.append(1, (unsigned)tmp);
        std::cout << "cout+for: " << (unsigned)tmp << std::endl;
        if(i<9)
            str_output.append(1, '-');
    }
    std::cout << std::endl << "cout+str_append: " << str_output  << std::endl;

    return 0;
}

Compiling and running the program gives the following output:

cout+for: 65
cout+for: 66
cout+for: 67
...

cout+str_append: A-B-C-D-E-F-G-H-I-J

The desired output is:

cout+str_append: 65-66-67-68-...
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Advice -- [you could have whittled this down to a tiny program](http://coliru.stacked-crooked.com/a/18359f74b56f8d34), attempting to create a string from a number. Possibly you could have figured this out yourself by doing as such. The loop, hyphen character, hex string, etc. were unnecessary in creating a [mcve]. – PaulMcKenzie Nov 25 '18 at 14:20
  • Thank you for your comment, I realize that my (already stripped down) example could be made much more focused. I take that into account if a post a new question :) – user10668188 Nov 25 '18 at 14:51

2 Answers2

1

The method string::append accepts, among the various overload, a size_t and a char, see reference.

string& append (size_t n, char c);

Therefore, in your code line

str_output.append(1, (unsigned)tmp);

you are implicitly converting the unsigned tmp to a char, i.e., to a single letter. To obtain the output you want, you have to convert tmp to a string containing the number, and then append it to str_output. You can do that by using

str_output+=std::to_string(tmp);

instead of str_output.append(1, (unsigned)tmp);.

francesco
  • 7,189
  • 7
  • 22
  • 49
0

You have to change your string append to for the change from a number to its "string":

str_output.append(std::to_string(tmp));

It's not one character that you want to add, but a string representing the number.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • Thanks for your answer. I'm new to C++, so I cannot tell which of yours and francescos answer is the "proper" one. However my python-background favors the `str += "abc"` notation. – user10668188 Nov 25 '18 at 14:54
  • Both are the same, both append the string after your previous strings. – Matthieu Brucher Nov 25 '18 at 14:57