Combining vector with For Loop

Hi everybode !
I'm trying to use vector in combination with a for loop, so i can input several time before displaying the answer (witch is stored in a vector). But things dosent go the way a expected. I'm using CodeBlock in Windows environment. Can someone help me to figure out what's wrong with my code ?

I want this :
-----------------
Inter a city name : Paris
London
Sydney
Bamako
cout :> Paris London Sydney Bamako
------------------

The purpose is not how is the result. The purpose is to combine these two concepts together.

Finally, i'm sorry for my poor english.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream> // for the Output & Input stuff
#include <vector> // cause i'm going to use vectors
#include <string> // just in case
using namespace std;

int main()

{
    vector<string> villes; // to store all vectors
    string ville; // to store the user input strings
    int i;

    cout <<"Enter a city name : "; // prompt the user to type in a city name
    for (i = 0 ; i <5 ; i++) // looping 5 times, so he puts others cities names
{
    cin >> ville ; // store whatever the user typed in
    villes[i] = ville; // store all cities names in the vector
    //villes.push_back(ville); //another variant
}
    cout << villes[i] << endl; // print out all the cities names

    return 0;
    }
Instead of using villes[i] = ville Try villes.push_back(ville)
also instead of cout << villes[i] << endl; try this:
1
2
3
4
for (int i=0; i<5; i++)
{
cout<<villes[i]<<endl
}
Thank you sargon94 !
That helped me. I did this :
1- comment this line of code - > villes[i] = ville; // line 17
2- discomment this one -> //villes.push_back(ville); // line 18
3- put the COUT statement in a For Loop as you said.
Last edited on
There are other ways to do it also 1 using iterators ( c++98 or c++11 )and ranged-based for loop( c++11 )

1
2
3
4
5
6
7
8
9
10
11
//iterators 98
for(  std::vector<T>::iterator it = vector.begin(); it != vector.end(); ++ it )
std::cout << *it << std::endl;

//iterator 11
for( auto it = vector.begin(); it != vector.end(); ++it )
std::cout << *it << std::endl;

//ranged-based for loop 11
for( const auto &it : vector )
std::cout << it << std::endl;
Ok giblit, I'll try it when I get into pointers. But for now in my book i didnt see anywhere something about ITERATOR ! I'm actually in Vector chapter. Anyway thank you for your advice
Topic archived. No new replies allowed.