mercredi 25 avril 2018

c++: Vectors, Averages and Txt

Okay, I finished this code with my goal of making a vector that pulls data from a text file and displays it.

Now I've begun adding to it, but I'm stuck and need help please. My next goal was to add up the votes and display the percent of votes EACH candidate received and then display the winner at the end. This is what I have so far.

EDIT: by the way, I have no errors...I just need help with my content.

#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;
}

and here is the text file I'm pulling from

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

Aucun commentaire:

Enregistrer un commentaire