Easiest way to convert int to string in C++

后端 未结 28 1757
甜味超标
甜味超标 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:19

    Use:

    #include
    #include
    
    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;
    }
    

提交回复
热议问题