2

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?

4

2 回答 2

3

你得到相同的输出,因为你所有的字符串都指向同一个地方——即你的str变量。您应该使用缓冲区str的数据创建新字符串,如下所示:

std::string *ps = new string(str);

delete ptr完成此操作后,当您不再需要字符串时,不要忘记通过在函数末尾调用每个字符串指针来删除分配的字符串。

于 2012-06-28T02:49:26.957 回答
0

我会给你一个线索:std::string *ps = &str这是一个非常糟糕的主意。每个指针都需要自己的内存。

于 2012-06-28T02:47:30.030 回答