I am a beginner in C++ and am working on a (supposedly SIMPLE) assignment, but it is making my head hurt...
I am familiar with C# and Java, where dynamic arrays are allowed, and other neat things such as foreach loops exist...
The program consists of reading data from a file that looks like this:
5 Johnson 5000 Miller 4000 Duffy 6000 Robinson 2500 Ashton 1800
The first line is always the number of "candidates" followed by repeating name/number of votes for that candidate (each following line respectively). The program has a limit of 20 candidates - I assume this is because dynamic arrays are not allowed so we must create fixed sized arrays to hold each type of data.
I am basically looking to read the first line, store it in a variable which will be used as my loop iteration limit, and store all the names in one array then store all the numbers in a second array to treat them.
Here is a small test snippet that I made when I try to read the file. It works but it generates an infinite loop :(
int main() {
string candidateNames[21];
double votesReceivedPerCandidate[21];
ifstream infile("votedata.txt");
while (!infile.eof()) {
string firstLine;
int numberofCandidates;
getline(infile, firstLine);
numberofCandidates = atoi(firstLine.c_str());
for (int x = 0; x < numberofCandidates; x++) {
cout << "hello!";
}
}
}
I am very sleep deprived right now, and not even sure if I am thinking about this the right way.
My questions are:
using C++, how would you read just the first line and then use the number from that line as a condition in a
for
loop? (also - is afor
loop the best option for this? how would you set it up?)how would you setup the loop above to read the file and store one entry into one array, the next entry into a second array, and repeat that process in pairs? (the same way as if you deal cards to 2 people)?