Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <sstream>
- #include <vector>
- #include <string>
- using namespace std;
- //declaring struct and members
- struct Candidate {
- string name;
- int votes;
- Candidate(string n, int v) : name(n), votes(v) {}
- };
- //handling data
- ostream& operator<<(ostream& os, const Candidate& c) {
- return os << c.name << ':' << c.votes;
- }
- int main() {
- //opening text file
- ifstream fin("candidates.txt");
- //dynamic array(vector) to read file
- vector<Candidate> candidates;
- //for lines of text
- string line;
- //for later calculations
- int numberOfCandidates = 0;
- //for later calculations
- int sum = 0;
- //while for instructions on what to do with text
- while (getline(fin,line)) {
- //input stream class to operate on strings.
- istringstream iss(line);
- string name;
- getline(iss, name, ',');
- int votes;
- iss >> votes;
- if (iss >> name >> votes)
- {
- sum += votes;
- numberOfCandidates++;
- }
- //add a new element to the vector each time a new integer is read
- candidates.push_back({ name, votes });
- }
- double average = (double)sum / (double)numberOfCandidates;
- for (const auto& c : candidates)
- cout << c << 'n'<< sum << 'n' ;
- cin.clear(); // reset any error flags
- cin.ignore(32767, 'n'); // ignore any characters in the input buffer until we find an enter character
- cin.get(); // get one more char from the user
- return 0;
- }
- Iron Man, 487
- Captain America, 568
- The Hulk, 17
- Black Widow, 542
- Spider Man, 309
- Scarlet Witch, 184
- Winter Soldier, 237
- Just Thor, 491
- The Falcon, 319
Add Comment
Please, Sign In to add comment