0

Vector Lists

HY ALL, I JUST COMPILED THIS CODE BUT IT WONT GIVE ME THE EXPECTED OUTPUT. Please help to debug. #include <iostream> #include <vector> #include <string> using namespace std; int main() { vector<string> stringList; vector<string>::iterator stringListIterator; for(stringListIterator = stringList.begin(); stringListIterator != stringList.end(); ++stringListIterator) { cout << "Enter a string" ; string stringName; cin >> stringName; stringList.push_back(stringName); if(stringList.size() == 10) { break; } } for(stringListIterator = stringList.begin(); stringListIterator != stringList.end(); ++stringListIterator) { cout << *stringListIterator; cout << endl; } return 0; }

8th Oct 2019, 8:14 PM
Dianah Delisile
Dianah Delisile - avatar
8 Answers
+ 2
Yes the vector size is '0' == empty, so there's nothing to iterate over in the input section. unsigned int mynum = 12; // or put 12 or what ever you like in the for loop, up to you. for(unsigned int x = 0; x < mynum; x++) // use this. { cout << "Enter a string" ; string stringName; cin >> stringName; stringList.push_back(stringName); if(stringList.size() == 10) { break; } }
8th Oct 2019, 8:57 PM
rodwynnejones
rodwynnejones - avatar
0
Your stringList is empty, there's nothing to iterate over.
8th Oct 2019, 8:25 PM
rodwynnejones
rodwynnejones - avatar
0
I assumed that the vector was initialized to vector.size = 0 at declaration, and returns a pointer to the base address. The first for loop is my attempt at initializing the vector values to 10 using the if statement in the loop.
8th Oct 2019, 8:29 PM
Dianah Delisile
Dianah Delisile - avatar
0
https://code.sololearn.com/ck3PJ8lO0ujb/?ref=app This displays the size of the vector after declaration, all other statements are put within comments.
8th Oct 2019, 8:32 PM
Dianah Delisile
Dianah Delisile - avatar
0
Hy, I managed to revise my code. initial Code for(stringListIterator = stringList.begin(); stringListIterator = stringList.end(); ++stringListIterator) //stringListIterator = stringList.begin() == stringListIterator != stringList.end(), therefore doesn't enter the for-block New Code using while loop https://code.sololearn.com/cvvN1YSnsDMO
8th Oct 2019, 9:11 PM
Dianah Delisile
Dianah Delisile - avatar
0
ah but what is someone enters something other than Y/y/N/n?
8th Oct 2019, 9:23 PM
rodwynnejones
rodwynnejones - avatar
0
In that case an assert macro should do the trick
8th Oct 2019, 9:26 PM
Dianah Delisile
Dianah Delisile - avatar
0
Although I class myself as a beginner...I am aware that a assert macros are used for debugging and are normally disabled/'switch off' in the production/final version of progs.
8th Oct 2019, 9:41 PM
rodwynnejones
rodwynnejones - avatar