1

I'm trying to combine all the elements inside a vector as a new string but I can't get the example how to do this. Most of the examples are concatenating between vectors and also in C++ std::cout. I'm not sure how to do it in MFC VC++.

Let's say I have a vector (in CString) with the elements I am a naughty boy. How can I combine them and saved them as a

CString str;

str = "I am a naughty boy"

Edited:

struct REVLISTDATA {
CString str_;
REVLISTDATA(CString str_element) : str_(str_element) {}
};
std::vector<REVLISTDATA> vec;

1 Answers1

2

If I am well understood your request, here is an approach:

for (size_t i = 0; i < vec.size(); ++i)
{
    str.AppendFormat(vec.at(i));
    if (i < vec.size() - 1)
        str.AppendFormat(_T(" "));  // spaces between words
}

presuming that your vec is std::vector<CString>

Edit: So, instead of str.AppendFormat(vec.at(i)); you should use str.AppendFormat(vec.at(i).str_);

Later edit: I have tried the following code and work ok:

struct REVLISTDATA
{
    CString str_;
    REVLISTDATA(CString str_element) : str_(str_element) {}
};

std::vector<REVLISTDATA> vec;

vec.push_back(REVLISTDATA("I"));
vec.push_back(REVLISTDATA("am"));
vec.push_back(REVLISTDATA("a"));
vec.push_back(REVLISTDATA("naughty"));
vec.push_back(REVLISTDATA("boy"));

CString str;
for (size_t i = 0; i < vec.size(); ++i)
{
    str.AppendFormat(vec.at(i).str_);
    if (i < vec.size() - 1)
        str.AppendFormat(_T(" "));  // spaces between words
}

So, I guess you exception is coming from other way.

Flaviu_
  • 1,285
  • 17
  • 33
  • yes, I have updated the vector in the question, it is in CString, correct?? But there is an error on this line `str.AppendFormat(vec.at(i));` and the output shows _error C2664: 'void ATL::CStringT>>::AppendFormat(const wchar_t *,...)': cannot convert argument 1 from 'REVLISTDATA' to 'UINT'_ – Joshua_0101 Nov 11 '20 at 08:51
  • I tried to put other string inside the vector and it get this error _0xC0000005: Access violation reading location_. – Joshua_0101 Nov 12 '20 at 06:08
  • I guess you are trying to access an object that don't exist. I'll prepare a little bit later a piece of code for you. – Flaviu_ Nov 12 '20 at 07:28
  • Found the root cause, it is the mistake when I push_back the string into the vector. The code works fine! – Joshua_0101 Nov 12 '20 at 14:50