mardi 9 juillet 2019

Passing a map to as a function parameter

So I'm attempting to pass a map to a function. I have checked the map and it has the data in it in main. But when I pass it to the function it stops as soon as it tries to initiate the iterator. I've tried just passing it and passing by reference and get the same result. The code compiles but fails at the quizUser function. The text file has StateName,Capital in that fashion for all 50 states.

#include <iostream> 
#include <fstream>
#include <map>
#include <string>
#include <time.h>
#include <algorithm>
#include <utility>

using namespace std;
map<string, string> populateMap();
pair<int, int> quizUser(map<string, string> USA);

int main()
{

pair<int, int> score; // pair to hold Win / Loss record
map<string, string> stateCapitals; // Map to hold data

cout << "This program will quiz you your knowledge of state capitals in the USA\n\n";

stateCapitals = populateMap(); // calling function to populate map from .txt file
score = quizUser(stateCapitals); // function to quiz user

cout << "\nCorrect Answers: " << score.first;
cout << "\nWrong Answers: " << score.second;
cout << endl;

system("pause");
return (0);
}






map<string, string> populateMap()
{
string tempState; // temp variable to hold state name
string tempCapital; // temp variable to hold state capital
map<string, string> newMap;

ifstream infile;
infile.open("StateCapitals.txt");

while (infile)
{
    getline(infile, tempState, ',');
    getline(infile, tempCapital);
    newMap[tempState] = tempCapital; // creating map from temp state and capital
}
return newMap;
}


pair<int, int> quizUser(map<string, string> USA)
{
    string lcCorrect;
    string userAnswer;
    pair<int, int> record = { 0 , 0 }; // Win / Loss
    srand(time(NULL)); // initiating time based seed for rand

    for (int i = 0; i < 5; i++)
{
    map<string, string>::iterator it = USA.begin(); // initiating iterator
    advance(it, rand() % USA.size()); // advancing the iterator a random value
    lcCorrect = it->second; // storing the answer in a temp value
    transform(lcCorrect.begin(), lcCorrect.end(), lcCorrect.begin(), ::tolower); // transforming correct answer into all lower case for comparison

    cout << "What is the state capital of " << it->first << ":";
    cin >> userAnswer; // user answer input
    transform(userAnswer.begin(), userAnswer.end(), userAnswer.begin(), ::tolower); // transforming user answer into all lower case for comparison

    if (userAnswer == lcCorrect) // correct answer
    {
        cout << "That is correct!!\n";
        record.first += 1;
    }
    else // incorrect answer
    {
        cout << "That is WRONG!!\n";
        record.second += 1;
    }
}
return record;
}

code -1073741676.

Aucun commentaire:

Enregistrer un commentaire