How to construct a std::string from a std::vector?

C++03 std::string s; for (std::vector<std::string>::const_iterator i = v.begin(); i != v.end(); ++i) s += *i; return s; C++11 (the MSVC 2010 subset) std::string s; std::for_each(v.begin(), v.end(), [&](const std::string &piece){ s += piece; }); return s; C++11 std::string s; for (const auto &piece : v) s += piece; return s; Don’t use std::accumulate for string concatenation, … Read more

std::string::c_str() and temporaries

The pointer returned by std::string::c_str() points to memory maintained by the string object. It remains valid until a non-const function is called on the string object, or the string object is destructed. The string object you’re concerned about is a temporary. It will be destructed at the end of the full expression, not before and … Read more

I want to convert std::string into a const wchar_t *

First convert it to std::wstring: std::wstring widestr = std::wstring(str.begin(), str.end()); Then get the C string: const wchar_t* widecstr = widestr.c_str(); This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.

Padding stl strings in C++

std::setw (setwidth) manipulator std::cout << std::setw (10) << 77 << std::endl; or std::cout << std::setw (10) << “hi!” << std::endl; outputs padded 77 and “hi!”. if you need result as string use instance of std::stringstream instead std::cout object. ps: responsible header file <iomanip>

What are some algorithms for comparing how similar two strings are?

What you’re looking for are called String Metric algorithms. There a significant number of them, many with similar characteristics. Among the more popular: Levenshtein Distance : The minimum number of single-character edits required to change one word into the other. Strings do not have to be the same length Hamming Distance : The number of … Read more

Concatenating strings doesn’t work as expected [closed]

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar: std::string c = “hello” + “world”; This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do … Read more

How do you convert CString and std::string std::wstring to each other?

According to CodeGuru: CString to std::string: CString cs(“Hello”); std::string s((LPCTSTR)cs); BUT: std::string cannot always construct from a LPCTSTR. i.e. the code will fail for UNICODE builds. As std::string can construct only from LPSTR / LPCSTR, a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA as an intermediary. CString cs … Read more