1

For context, I am working on a reward system program for a store. I have a file which contains a list of items with the points the customer earns underneath the name of each item. Here is what the file contains:

rolling papers
1
lighter
1
silicone pipe
5
glass pipe
8
water pipe
10

I am trying to read from the file into two different variables then store those variables in a vector of pairs. But I've noticed that when I output the pairs from the vector the first letter of the item is missing, and the points are completely off. I've tried to change the point to a char instead of an int, and did the same in the paired vector. Both gave similarly inaccurate/strange outputs. What am I doing wrong here? Thanks guys. Here is the part of my program where I'm trying to store the items/points in a paired vector:

    int answer;
    int points;
    std::string tempName;
    std::string name;
    std::string item;
    std::ifstream inFS;
    std::vector<std::string> nameList;
    std::vector<std::pair<std::string, int>> pairedList;
    std::cout << "Would you like to add points to a member's name? If not, input 0 to look at other options!" << std::endl;
    std::cout<< "Otherwise, input 1 to continue to the point system." << std::endl;
    std::cin >> answer;
    if (answer == 0)
        options();
    if (answer == 1) {
        inFS.open("items.dat");
        if (inFS.is_open())
            std::cout << "File opened successfully." << std::endl;
        while (std::getline(inFS, item)) {
            inFS >> points;
            pairedList.push_back(make_pair(item, points));
        }
        if (!inFS.eof())
            std::cout << "Not able to reach end of file" << std::endl;
        inFS.close();
        for (int i = 0; i < pairedList.size(); i++)
            std::cout << pairedList[i].first << " " << pairedList[i].second << std::endl;
        exit(1);
    }
} 
wawa
  • 127
  • 5

1 Answers1

1

Try changing the inFS >> points for another std::getline(inFS, points_str) (notice you need a std::string points_str{};); then you can do a make_pair(item, std::stoi(points_str)). [Demo]

#include <iostream>  // cout
#include <string>  // getline, stoi

int main()
{
    std::string item{};
    std::string points{};
    while (std::getline(std::cin, item))
    {
        std::getline(std::cin, points);
        std::cout << "item = " << item << ", points = " << std::stoi(points) << "\n";
    }
}
rturrado
  • 7,699
  • 6
  • 42
  • 62