Issues with Vectors

I'm trying to allow someone to input variables into a shopping list so you can then output them after you are done inputting by inputting * The program is giving me a segmentation fault for some reason. Please help! :(

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//g++ -std=c++11 vectors.cpp
#include<string>
#include<iostream>
#include<vector>
using namespace std;
int main() {
int i;
string newItem;
vector<string> shoppinglist;

shoppinglist.push_back("a");
cout << "Enter your shopping list. Enter * to indicate you are done." << endl;
while(newItem != "*"){
cin >> newItem;
shoppinglist[i] = newItem;
i++;
}

cout << "Here is your list:" << endl;
for(unsigned int i = 0; i < shoppinglist.size(); i++) {
cout << shoppinglist[i] << endl;
}
return 0;
}
1
2
3
4
5
6
7
shoppinglist.push_back("a");
cout << "Enter your shopping list. Enter * to indicate you are done." << endl;
while(newItem != "*"){
cin >> newItem;
shoppinglist[i] = newItem;
i++;
}


Should be :
1
2
3
4
5
6
7
8
9
i = 0;

cout << "Enter your shopping list. Enter * to indicate you are done." << endl;
while(newItem != "*"){
cin >> newItem;
shoppinglist.push_back("a");
shoppinglist[i] = newItem;
i++;
}
Last edited on
Topic archived. No new replies allowed.