I want to enter five strings and push them into a vector. But this doesn't work for me. If I do it like with the bigger code below, I get a vector size of 5 and can only enter 4 strings. But if I change it so it says
for(int n=0; n<=5; n++)
This results in me being able to input 5 strings, but if I call investments.size() it returns a value of 6. And if I print every element it will start by printing an empty string first, then print the 5 that I've entered.
So it seems that when my loop finishes I get an extra input and it pushes it into the vector. Is it because of the getline() line? Will this run and input an empty string into my vector as my loop finishes?
int main(){
using namespace std;
vector<string> investments;
vector<double> andel;
double procent;
int kapital;
cout << "Hur stort kapital ska investeras?" << endl;
cin >> kapital;
cout << investments.size() << endl;
cout << "Skriv in dina fonder som du ska spara i. En i taget." << endl;
for(int n=0; n<5; n++){
string bolag;
getline(cin, bolag);
investments.push_back(bolag);
}
cout << "size of investments: " << investments.size() << endl;
for(string s : investments) cout << s << endl;
}
Aucun commentaire:
Enregistrer un commentaire