I am learning C++ and there is a question in the book.
Q: Write a program that defines a vector of pointers to strings. Read the vector, printing each string and its corresponding size.
Code:
vector<string*> v;
string str;
cout<<"Enter your string:"<<endl;
while(cin >> str) // input
{
string *ps=&str;
v.push_back(ps);
}
vector<string*>::iterator iter=v.begin();
while( iter!=v.end()) // output
cout<< **iter++<<" "<<(**iter).size()<<endl;
When I input "a sd fgh", I expect the output to be "a 1; sd 2; fgh 3"; but the output is "fgh 3; fgh 3; fgh 3." Anyone know where is going wrong?