Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ STL
#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 7-Dec-12 6:34am
Edited 7-Dec-12 6:47am
v4
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
cout << str << endl;
to
cout << coll[i] << endl;
  Permalink  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

 for(int i = 0; i < 3; i++)
   cout << coll[i] << endl; 
 
The vector isn't in your output code!
  Permalink  
v2

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

  Print Answers RSS
0 OriginalGriff 299
1 Maciej Los 295
2 Sergey Alexandrovich Kryukov 230
3 Aajmot Sk 191
4 Sinisa Hajnal 166
0 OriginalGriff 7,760
1 Sergey Alexandrovich Kryukov 7,072
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,785


Advertise | Privacy | Mobile
Web01 | 2.8.1411023.1 | Last Updated 7 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100