0

I have one doubt. I have one object list with some data (in this case to store names).

I iterate the list: (pNames it is my list receive by parameter)

std::string names;
std::list<Names>::const_iterator it = pNames->begin();
while(it != pNames->end())
{
   std::cout << names << it->namesUser;
   ++it;
}

The problem: I need to save the all values of iterator in std::string to use this string on mysql query (for example select age from users where names in ('names');) In this momment with the `std::cout << names << it->namesUser; i can see all names in list but i cannot use the names variable in query for example. It only work with cout. I'm new with c++ programming, so what is the way to store all iterator values in string?

Thanks a lot.

Regards

5
  • 1
    Add names += it->namesUser; in the loop? Commented Mar 21, 2017 at 12:04
  • 2
    @NathanOliver Plus a suitable delimiter, I assume. Commented Mar 21, 2017 at 12:04
  • Hi. I try this before but when i print the names variable to test it appear with ' ? ' symbol and not the all names return by iterator Commented Mar 21, 2017 at 12:08
  • Please post a minimal reproducible example, including expected and actual output. Commented Mar 21, 2017 at 12:17
  • The problem is solved. Thanks a lot ;) Commented Mar 21, 2017 at 13:36

1 Answer 1

1

Use std::ostringstream instead of std::cout

http://www.cplusplus.com/reference/sstream/ostringstream/

#include <sstream>

....

std::ostringstream names;
std::string delimiter = ",";
std::list<Names>::const_iterator it = pNames->begin();
if (it != pNames->cend())
{
    names << it->pNames;
    it++;
}
while(it != pNames->cend())
{
    names << delimiter << it->namesUser;
    ++it;
}
std::string result = names.str();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. It solved my problem. I already use stringstream but didn't know the osstringstream. Best regards ;)
happy to help :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.