string not added to list

#include <string>
#include <sstream>
#include <iostream>
#include <list>
using namespace std;



int main () {
int test [5] = {0, 1, 2, 3, 4};
list<string> listTest;
string str2 = " (";
string str = "fail";
string temp = "word";
int x = 5;

for (int i = 0; i < 5; i++) {
x = test[i];
stringstream convert (stringstream::in | stringstream::out);
convert << x;
convert >> temp;
temp = convert.str();
convert.clear();
convert.str("");
str = temp + str2;
//it gets into str fine and then when you go to put
//it into the list something is messing up.
cout << str << endl;
listTest.push_back(str);
}

list<string>::iterator itr = listTest.begin();
string tempString = *itr;
while (itr != listTest.end()){
cout << tempString << endl;
++itr;
}

return 0;
}


for the output I'm getting:

0 (
1 (
2 (
3 (
4 (
0 (
0 (
0 (
0 (
0 (


So basically, the string str is being created fine, but then when I go to add it to the list using push_back() for some reason it's not being added correctly and I can't figure out why. Any ideas? Thanks so much!
maybe you can use:

std::string str

Sometimes a compilers get's confused if you don't use
std::

How far do you want it too convert?

Your
for (int i = 0; i < 5; i++)
tells me (and your compiler) you want to loop 5 times.

Last edited on
The problem is in your while loop. tempString is the first element, which you keep printing, you need to use *itr

1
2
3
4
5
6
list<string>::iterator itr = listTest.begin();
 string tempString = *itr;
 while (itr != listTest.end()){
 cout << tempString << endl;
 ++itr;
 }

to
1
2
3
4
5
list<string>::iterator itr = listTest.begin();
 while (itr != listTest.end()){
 cout << *itr << endl;
 ++itr;
 }
Topic archived. No new replies allowed.