简体   繁体   中英

(C++) - Associating strings with values read in from a file

I am trying to get a value associate with a string inside a file called invoice1.txt

invoice1.txt

hammer#10.00
saw#20.00

So for example, when I lookup "hammer" I would like the expression to evaluate to 10.00.

My code so far

string search;
ifstream inFile;
string line;
double price;

inFile.open("invoice1.txt");

if(!inFile)
{
cout << "Unable to open file" << endl;
return 0;
}
else
{
    int pos;
    while(inFile.good())
    {
        getline(inFile,line);
        pos=line.find(search);
        if(pos!=string::npos)
        {
            cout<<"The item "<<search<<" costs: "// code to get the price
        }
    }
}


system("pause");

This is the output I am aiming for:

The item hammer costs: 10.00

The summerise, my question is:

How can I associate values with one another that are read in from a file, so I can get a price for an item without having to reparse the file and find it again?

This is what std::map is for.

What you want to do is break your problem down into multiple stages. Here is a simple set of steps that should help you (there are better ways, but I'm trying to keep things simple here).

I've added some lines to explain how to use std::map, in case you're not familiar.

  1. Read the file line by line.
  2. For each line that is read in, get the value after the '#' character.
  3. Add the value to the map, using the string before '#' as the key...

    priceMap[key] = price; // for example, this might evaluate to: myMap["hammer"] = 10.00

  4. When you want to use the value, simple give the map you're key.

    std::cout << priceMap["hammer"];

What do you search in line from file? You have to search for character # and split your string into two parts.

getline(inFile,line);
pos=line.find('#');
if(pos!=string::npos)
   cout<<"The item "<<line.substr(0,pos)<<" costs: " << line.substr(pos+1,line.size()-1) << endl;// code to get the price

You can save item name and price in different variables if you want. If you want to do something more with a string, read this for further instructions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM