tags:

views:

88

answers:

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

// Simple example uses type int

main()
{
   list<string > L;
   L.push_back("test");              // Insert a new element at the end

 L.push_back("testinggggg"); 
 L.push_back("example"); 
   list<string>::iterator i;

   for(i=L.begin(); i != L.end(); ++i) {
       string test = *i;
       cout << test;
   }
   return 0;
}

I am not getting any output if I use the above program and if I change the string test=*i to cout << *i << " "; it works. What is the problem with this?

A: 

This should not even compile (and it doesn't, on a recent g++).

i is an iterator over a list<int>, so *i is of type int. If you assign this to a string like this:

string test=*i;

the compiler will look for a conversion from int to string. There is no such conversion defined in the standard library.

Thomas
A: 

Your last for loop you attempt to set the string test to the value of an integer.

You should just try cout << *i << endl;

freefallr
sorry that was my mistake and i have changed the programm ..still same error??
raj
you might try reading i into a temporary int variable with int myInt = *i; cout << myInt << endl;
freefallr
Can you tell us what exactly the error message is? Is it from the compiler or are you just not getting any output?
freefallr
A: 

It works for me and produces the output:

testtestingggggexample

You're missing spaces between the words and an endl at the end, but the output is there as one would expect.

jkugelman$ g++ -Wall -o iterator iterator.cpp 
iterator.cpp:8: warning: ISO C++ forbids declaration of ‘main’ with no type
jkugelman$ ./iterator 
testtestingggggexamplejkugelman$ 
John Kugelman
A: 

Working for me. I got this output

testtestingggggexample

I am on Suse g++ 3.4.3 version.

Manoj R