Easiest way to convert int to string in C++

后端 未结 28 1795
甜味超标
甜味超标 2020-11-21 06:42

What is the easiest way to convert from int to equivalent string in C++. I am aware of two methods. Is there any easier way?

(1)



        
28条回答
  •  难免孤独
    2020-11-21 07:36

    You use a counter type of algorithm to convert to a string. I got this technique from programming Commodore 64 computers. It is also good for game programming.

    • You take the integer and take each digit that is weighted by powers of 10. So assume the integer is 950.

      • If the integer equals or is greater than 100,000 then subtract 100,000 and increase the counter in the string at ["000000"];
        keep doing it until no more numbers in position 100,000. Drop another power of ten.

      • If the integer equals or is greater than 10,000 then subtract 10,000 and increase the counter in the string at ["000000"] + 1 position;
        keep doing it until no more numbers in position 10,000.

    • Drop another power of ten

    • Repeat the pattern

    I know 950 is too small to use as an example, but I hope you get the idea.

提交回复
热议问题