Easiest way to convert int to string in C++

2018-12-31 02:10发布

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)

int a = 10;
char *intStr = itoa(a);
string str = string(intStr);

(2)

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

25条回答
深知你不懂我心
2楼-- · 2018-12-31 02:34
namespace std
{
    inline string to_string(int _Val)
    {   // convert long long to string
        char _Buf[2 * _MAX_INT_DIG];
        snprintf(_Buf, "%d", _Val);
        return (string(_Buf));
    }
}

you can now use to_string(5)

查看更多
浪荡孟婆
3楼-- · 2018-12-31 02:34

I think, using stringstream is pretty easy.

 string toString(int n)
 {
   stringstream ss(n);
   ss << n;
   return ss.str();
 }

 int main()
 {
    int n;
    cin>>n;
    cout<<toString(n)<<endl;
    return 0;
 }
查看更多
无与为乐者.
4楼-- · 2018-12-31 02:35

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 pattern

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

查看更多
与风俱净
5楼-- · 2018-12-31 02:36

sprintf() is pretty good for format conversion. You can then assign the resulting C string to the C++ string as you did in 1.

查看更多
骚的不知所云
6楼-- · 2018-12-31 02:37
#include "stdafx.h"
#include<iostream>
#include<string>
#include<string.h>


std::string intToString(int num);

int main()
{

    int integer = 4782151;

    std::string integerAsStr = intToString(integer);

    std::cout << "integer = " << integer << std::endl;
    std::cout << "integerAsStr = " << integerAsStr << std::endl;


    return 0;
}

std::string intToString(int num)
{
    std::string numAsStr;

    while (num)
    {
        char toInsert = (num % 10) + 48;
        numAsStr.insert(0, 1, toInsert);

        num /= 10;
    }

    return numAsStr;
}
查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 02:38

Use:

#define convertToString(x) #x

int main()
{
    convertToString(42); // Returns const char* equivalent of 42
}
查看更多
登录 后发表回答