I've been practicing passing a txt file into Dynamically Allocated Arrays, couldn't figure it out so went with Vector in the meantime and have the code below so far without error using this text file with a list of Characters and the votes they've received.
Now I would like to display (cout)their Name, Number of Votes, and Percent from total Votes each got
Then (cout) the "winner"
I've practiced some percentage code/displaying before, but I think I'm making this harder in my head than it needs to be.
What would be the most productive way to achieve this?
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
usingnamespace std;
int main() {
vector<int> numbers; //to hold votes
ifstream in("candidates.txt"); //input file stream
int number; //variable to hold votes while being read
while (in >> number) {
numbers.push_back(number);
}
in.close();
{
vector<string> names; //to hold names
ifstream in("candidates.txt"); //input file stream
string name; //variable to hold names while being read
while (in >> name) {
names.push_back(name);
}
}
in.close();
}
Not knowing what the input actually looks like it makes it hard to say how it should be read. Post the input file or at least a small portion of it.
The two while loops should be combined into one and both the name and number should be read at the same time.
The {}s at line 27 and 40 are OK, but not really needed. There is no reason to limit the scope of what is between them.
A suggestion is to finish a line of code and put the opening { on the next line and the closing } in the same column. Along with proper indenting it makes the code easier to read, but more important it makes it easier to find a missing }.
This may be a personal preference, but I like to define my variables at the beginning of the function. This way I know where they are at instead of looking through lines of code to find them.
Your code may compile without error, but I do not believe it will run correctly based on opening and closing the file twice and your while loops, which BTW are done properly for reading a file.
Well that makes a big difference. This can be done, but as is there is no distinct way to distinguish the name from the number. If there was a comma at teh end of the name or maybe a tab between the name and number it would be easy to use "std::getline".
If you can change the input that would make it easy otherwise it will take some work.