Hello there,
I have been working on this assignment for class where we have to convert to use an STL vector instead of an array. We also have to complete this my using iterators, no square brackets or use of push_back or at().
My problem that I am dealing with is at my readData function. I am trying to get it to accept a line from the use and store it under name but cin.getline is not working for me. Cant seem to figure it out or maybe I am missing something simple? Do you know a way to get it to accept a line of characters?
Yeah, it was my intension to have a line of characters. I believe that I am supposed to keep that variable type. This is good though, I look into that. Its been a long while since the last time I tried to program.
Edit: Yes that name field must remain as a c-string
I see what you did there seeplus and it looks good but it my fault I didnt include more information. In the directions its stated that a size parameter should not be used being that a vector knows its own size and can increase in its own. Thats where I have to figure out how to get it to read a line of characters and store them into char name.
#include <iostream>
#include <vector>
usingnamespace std;
struct Highscore {
vector <char> name;
int score {};
};
size_t getVectorSize();
void readData(vector<Highscore>& scores);
int main()
{
constauto size {getVectorSize()};
vector<Highscore> scores(size);
readData(scores);
for (constauto& [name, score] : scores) {
for (constauto& ch : name)
std::cout << ch;
std::cout << " " << score << '\n';
}
}
size_t getVectorSize() {
size_t size {};
cout << "How many scores will you enter?: ";
cin >> size;
cin.ignore();
return size;
}
void readData(vector<Highscore>& scores)
{
for (auto i = scores.begin(); i != scores.end(); ++i) {
cout << "Enter the name for score #" << i - scores.begin() + 1 << ": ";
for (char ch {}; (ch = cin.get()) != '\n'; )
i->name.emplace_back(ch);
cout << "Enter the score for score #" << i - scores.begin() + 1 << ": ";
cin >> i->score;
cin.ignore();
}
cout << '\n';
}
How many scores will you enter?: 3
Enter the name for score #1: qwe rty
Enter the score for score #1: 1
Enter the name for score #2: asd fgh
Enter the score for score #2: 2
Enter the name for score #3: zxc vbn
Enter the score for score #3: 3
qwe rty 1
asd fgh 2
zxc vbn 3