-1

Hello as the title suggests I want to convert a vector,

 std::vector<std::string>

to a c-style string, like

char* buffer.

The reason I want the vector to become a c-style string is because I am currently working with the WinApi, and I am specifically trying to use

SetWindowTextA()

which does not take a vector. And yes, I have to read the data in to a string vector first so there's not really anything I can change there. So if you could help me or point me in the right direction I'd be more than happy

EDIT: To further explain: Yes I will get several string loaded in to the vector. I simply want all those strings to combine in to one string.

Greetings, ye546

ye546
  • 41
  • 6
  • Can you give an example how should the strings be combined into one? – Quimby Jan 09 '21 at 17:41
  • 1
    `char*` is a single string, but you have several strings. You do want to insert `\n` between them? – HolyBlackCat Jan 09 '21 at 17:42
  • Is l it should be easy to Google how to join a vector of string to a single string. And then just call .data(). – JHBonarius Jan 09 '21 at 17:43
  • 3
    `std::stringstream ss; auto sep = ""; for (auto&& s : v) { ss << sep << s; sep = " "; } SetWindowTextA(hwnd, ss.str().c_str());` – Eljay Jan 09 '21 at 17:46
  • Can you use `.c_str()`? – Surt Jan 09 '21 at 17:47
  • 1
    How should the strings be combined? – Galik Jan 09 '21 at 18:02
  • Why don't you access your vector by index and use `.c_str()`? i.e: `SetWindowTextA(myVec[0].c_str())`. Do you understand that a vector of std::string has many strings in it? – Vinícius Jan 09 '21 at 18:18
  • It often helps to divide problems into smaller pieces. In this case, you've come very close to doing that, but you are still looking at this as one problem. Your goal consists of [Combining a vector of strings](https://stackoverflow.com/questions/1985978/combining-a-vector-of-strings) followed by converting [std::string to char*](https://stackoverflow.com/questions/7352099/stdstring-to-char), does it not? – JaMiT Jan 10 '21 at 00:02

1 Answers1

0

So just combine the vector strings into a single string, then call c_str() to convert to a char*.

std::vector<std::string> vec;
...
std::string combined;
for (const auto& s : vec)
    combined += s;
WinAPI(combined.c_str());
john
  • 85,011
  • 4
  • 57
  • 81
  • `std::string::c_str` returns `const char *`. Use `&combined[0]` instead. – j__ Jan 09 '21 at 18:17
  • 2
    `SetWindowTextA` takes a `char const*`, so using [c_str()](https://en.cppreference.com/w/cpp/string/basic_string/c_str) is perfectly fine. – IInspectable Jan 09 '21 at 18:38