Reputation: 23
I have a problem with my exercise code. If I enter the name and score value the values aren't getting pushed into the vector. Here is my code:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
while(true)
{
vector<string> names = {"test"};
vector<int> scores = {0};
string name = "none";
int score = 0;
cin >> name >> score;
if(name == "print" && score == 0)
{
for(int i = 0;i<names.size();++i)
{
cout << "name:" << names[i] << " score:" << scores[i] << "\n";
}
}
if(name == "NoName" && score == 0)
{
break;
}
if (find(names.begin(), names.end(), name) != names.end())
{
cout << name << " found name in names, you can't use this name.\n";
}else{
names.push_back(name);
scores.push_back(score);
}
}
}
the else-statement where the values are getting pushed in the vector is getting called but it doesn't push the values in the vector.
Upvotes: 0
Views: 309
Reputation: 180435
Your issue here is names
and scores
are declared inside the while loop. That means every iteration they are constructed, used, and then destroyed. This means in every iteration you have fresh vectors. You need to move the vectors out of the loop so they persist through the entire execution of the loop.
vector<string> names = {"test"};
vector<int> scores = {0};
while(true)
{
string name = "none";
int score = 0;
...
}
Upvotes: 6