Why is push_back not working as intended? Pretty confused as to why it doesn't work with my current code below
using namespace std;
void addItem(vector<string>& STRING, string item)
{
STRING.push_back(item);
}
int main()
{
string item;
vector<string> STRING(100);
ifstream myFile;
myFile.open("food.txt");
if (myFile.is_open()) //code where I store my data into the array
{
int i = 0;
while (!myFile.eof())
{
getline(myFile, STRING[i]);
i++;
}
}
myFile.close();
cin >> item;
addItem(STRING, item);
int x = 0;
while(!STRING[x].empty()) //code to print the current array
{
cout << STRING[x];
printf("\n");
x++;
return 0;
}
}
Is there something wrong with how I initialized my array? Because when I used CodeBlocks, there were 0 errors and 0 warnings so I assumed it was fine until I ran it.
Your code does work. However you specified initial size of vector while creating it. Your vector starts with initial size of 100 elements. With that being said, you are indeed adding new element to the array, however push_back() is putting it right after already existing array - at 100th position.
You can avoid it by using defaul constructor
vector<string> STRING;
Also, I'll paste here my printList function, that will show you what the issue is with:
void printList(vector<string> &STRING)
{
cout << "size: " << STRING.size() << '\n';
for (int i = 0; i < STRING.size(); i++)
cout << i << ":" << STRING[i] << ", ";
cout << '\n';
}
@Edit: Fixed syntax error (Vector instead of vector). Thank you for pointing it out Christian Hackl!