I was experimenting with a direct method of dereferencing an iterator.
It works OK with numbers, cout gets confused (??) when the derefenced pointer is a string?
The code was supposed to stuff a vector, then read it out . I hacked up that original to do some troubleshooting and it came down to the iterator.

How can this method be used with a string? -or can it?

#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector <string> strv;

int main()
{
        string input;
        vector <string>::iterator itr = strv.begin();

        do
        {
                getline (cin,input);
        strv.push_back(input);
        }
        while(input !="x");
        cout << "exited first loop" << endl;

        while (itr != strv.end())
        {

                cout << *itr++  << endl;//cout crashes here

        }
return 0;
}

use this

cout << (*itr++).c_str() << endl;

Wrtie the "itr = strv.begin();" after the cout...

I think when you initialize itr = strv.begin(); at the beginning of the code the itr points a random value at memory and when cout attempts to write this value it causes an error.

But when you initialize the "itr" after the loop, the "itr" points the first user defined element in the list and when cout attempts to output this value it doesn't cause an error...

Wrtie the "itr = strv.begin();" after the cout...

I think when you initialize itr = strv.begin(); at the beginning of the code the itr points a random value at memory and when cout attempts to write this value it causes an error.

But when you initialize the "itr" after the loop, the "itr" points the first user defined element in the list and when cout attempts to output this value it doesn't cause an error...

you are correct in that it fails if you assign the itterator before you have placed any values into the vector.

Sometimes the stupidest things cause big problems!
It wasn't that cout didn't know what type it was dealing with, rather it was getting random "junk" as proposed by Fox.

The fix was simply to move the iterator intiialization to a line AFTER the vector had been stuffed.

The *itr++ deref as originally written works fine now.

Thanks for the replies!

#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector <string> strv;

int main()
{
        string input;

        do
        {
                getline (cin,input);
        strv.push_back(input);
        }
        while(input !="x");
        cout << "exited first loop" << endl;

        vector <string>::iterator itr = strv.begin(); //put itr init here instead
        while (itr != strv.end())
        {

                cout << *itr++  << endl;

        }
return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.