Guest User

Untitled

a guest
Apr 25th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <sstream>
  4. #include <vector>
  5. #include <string>
  6.  
  7. using namespace std;
  8.  
  9. //declaring struct and members
  10. struct Candidate {
  11. string name;
  12. int votes;
  13. Candidate(string n, int v) : name(n), votes(v) {}
  14. };
  15.  
  16. //handling data
  17. ostream& operator<<(ostream& os, const Candidate& c) {
  18. return os << c.name << ':' << c.votes;
  19. }
  20.  
  21.  
  22.  
  23. int main() {
  24.  
  25. //opening text file
  26. ifstream fin("candidates.txt");
  27.  
  28. //dynamic array(vector) to read file
  29. vector<Candidate> candidates;
  30.  
  31. //for lines of text
  32. string line;
  33.  
  34. //for later calculations
  35. int numberOfCandidates = 0;
  36.  
  37. //for later calculations
  38. int sum = 0;
  39.  
  40. //while for instructions on what to do with text
  41. while (getline(fin,line)) {
  42. //input stream class to operate on strings.
  43. istringstream iss(line);
  44. string name;
  45. getline(iss, name, ',');
  46. int votes;
  47. iss >> votes;
  48.  
  49.  
  50. if (iss >> name >> votes)
  51.  
  52. {
  53. sum += votes;
  54. numberOfCandidates++;
  55. }
  56.  
  57. //add a new element to the vector each time a new integer is read
  58. candidates.push_back({ name, votes });
  59. }
  60.  
  61. double average = (double)sum / (double)numberOfCandidates;
  62.  
  63. for (const auto& c : candidates)
  64. cout << c << 'n'<< sum << 'n' ;
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74. cin.clear(); // reset any error flags
  75. cin.ignore(32767, 'n'); // ignore any characters in the input buffer until we find an enter character
  76. cin.get(); // get one more char from the user
  77.  
  78. return 0;
  79. }
  80.  
  81. Iron Man, 487
  82. Captain America, 568
  83. The Hulk, 17
  84. Black Widow, 542
  85. Spider Man, 309
  86. Scarlet Witch, 184
  87. Winter Soldier, 237
  88. Just Thor, 491
  89. The Falcon, 319
Add Comment
Please, Sign In to add comment