Vector is crashing program

I made a vector and i wanted the user to enter names and then stop to stop, but after i do that the program outputs what i entered then crashes. It says the program has stopped working.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  #include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<string> strVect_one;

    string names;

    bool stop = false;

    cout << "Enter names" << endl;
    cout << "Type 'stop' to stop inputting" << endl;

    while(stop != true)
    {
        getline(cin, names);
        strVect_one.push_back(names);

        if(names == "stop" || names == "Stop")
        {
            stop = true;
        }
    }

    int vectSize = strVect_one.size();

    for(int i = 0; vectSize >= 1; i++)
    {
        cout << "Names: " << strVect_one[i] << endl;
    }
    
    return 0;
}
closed account (Dy7SLyTq)
line 31: for(int i = 0; i < vectSize; i++

personally i would try:
for(vector::iterator vi : strVect_one)
cout<<"Names: " << vi << endl;
for(vector::iterator vi : strVect_one) Im not sure what this does? i assume it does the same exact thing as what i have but can you explain iterator?
closed account (Dy7SLyTq)
iterator is a specialized variable used to move through a container, in this case a vector. in c++11 they came out with what they call a range-based for loop, which in other languages is typically called a foreach loop. im not sure if i did the condition correct (i havent needed to use it before) but if it doesnt im sure someone will correct me. but what it does is automatically iterate through the vector for you
The problem with the original code is that vectSize >= 1 will not change so if it is true when you reach the loop it will stay true. That means there is nothing preventing i from growing bigger than there are elements in the vector, which will eventually cause a crash. Using a loop condition i < vectSize is probably what you want.

If you want to use iterators, like DTSCode tried to show it will look something like this (without range-based for loop):
1
2
3
4
for(vector<string>::iterator it = strVect_one.begin(); it != strVect_one.end(); ++it)
{
	cout << "Names: " << *it << endl;
}

And using a range-based for loop it could look something like this:
1
2
3
4
for(string& str : strVect_one)
{
	cout << "Names: " << str << endl;
}

Note that in the range-based for loop you don't actually see the iterators but they are used behind the scene.
In c++11 you can do like this:

1
2
3
4
5
6
std::vector<std::string> svec;
svec.push_back("one");
svec.push_back("two");

for(const auto &elem : svec)
    std::cout << elem << std::endl;


auto is used to get the automatic type of the iterator. ( std::vector<std::string>::const_iterator )
Topic archived. No new replies allowed.