Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size_t convert/cast to string in C++ [duplicate]

Tags:

c++

string

Possible Duplicate:
How to convert a number to string and vice versa in C++

How do I convert an integral value to a string in C++?

This is what I've tried:

for(size_t i = 0;vecServiceList.size()>i;i++)
{
    if ( ! vecServiceList[i].empty() )
    {
        string sService = "\t" + i +". "+  vecServiceList[i] ;
    }
}

And here is the error:

invalid operands of types 'const char*' and 'const char [3]' to binary 'operator+'
like image 446
user881703 Avatar asked May 09 '12 04:05

user881703


People also ask

Can Size_t be a double?

Converting to double will not cause an overflow, but it could result in a loss of precision for a very large size_t value. Again, it doesn't make a lot of sense to convert a size_t to a double ; you're still better off keeping the value in a size_t variable.

Can you cast from a Size_t to int c?

Just use casting. You can safely convert size_t to int by checking its range before casting it. If it is outside the valid int range, you can't. Test against INT_MAX to ensure no possible signed integer overflow before casting it.

What does to_ string do in c++?

std::to_string in C++ It is one of the method to convert the value's into string. The to_string() method takes a single integer variable or other data type and converts into the string.

What is std :: string& in C ++?

std::string::data() in C++It returns a pointer to the array, obtained from conversion of string to the array. Its Return type is not a valid C-string as no '\0' character gets appended at the end of array. Syntax: const char* data() const; char* is the pointer to the obtained array.


1 Answers

You could use a string stream:

#include <sstream>

...


for (size_t i = 0; ... ; ...)
{
    std::stringstream ss;

    ss << "\t" << i << vecServiceList[i];

    std::string sService = ss.str();

    // do what you want with sService
}
like image 116
dreamlax Avatar answered Oct 25 '22 17:10

dreamlax