Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
	vector<char*> coll;
	char str[20];
	for(int i = 0; i < 3; i++)
	{
		cin >> str;
		coll.push_back(str);
	} 
	for(int i = 0; i < 3; i++)
		cout << coll[i]<< endl;
	return 0;
}
When I input 3 strings, why does the vector only catch the last one?
For example when the strings are "China","USA","Russia", the vector only get "Russia".
Posted
Updated 7-Dec-12 5:47am
v4

You should use std::string instead of char *.

You always push the same address (str) in the vector and since the vector contains pointers and not values, the values are not copied.

Thus you have added 3 time a pointer to the same address and since the content change at each iteration, at the end, you have the content of the last read string.

Igt is much more simple to use std::string that trying to uses pointers. Thus, you should replace vector<chart *> by vector<string> and your problem will be nicely solved.
 
Share this answer
 
The strings are succesfully added in the vector your problem is in printing them
Because you are printing str over and over (3 times) instead of printing coll[i].

Change this
C++
cout << str << endl;
to
C++
cout << coll[i] << endl;
 
Share this answer
 
v3
for(int i = 0; i < 3; i++)
  cout << coll[i] << endl;


The vector isn't in your output code!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900