gpt4 book ai didi

c++ - (C++) - 将字符串与从文件中读取的值相关联

转载 作者:行者123 更新时间:2023-11-30 02:49:09 25 4
gpt4 key购买 nike

我正在尝试获取与名为 invoice1.txt 的文件中的字符串关联的值

invoice1.txt

hammer#10.00
saw#20.00

例如,当我查找“hammer”时,我希望表达式的计算结果为 10.00。

到目前为止我的代码

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");

这是我的目标输出:

The item hammer costs: 10.00

夏天,我的问题是:

如何将从文件中读入的值相互关联起来,这样我就可以获得商品的价格,而无需重新分析文件并再次找到它?

最佳答案

这就是std::map是为了。

您要做的是将您的问题分解为多个阶段。以下是一组应该对您有所帮助的简单步骤(有更好的方法,但我尽量让事情变得简单)。

我添加了一些行来解释如何使用 std::map,以防您不熟悉。

  1. 逐行阅读文件。
  2. 对于读入的每一行,获取“#”字符后的值。
  3. 将值添加到映射中,使用“#”之前的字符串作为键...

    priceMap[key] = 价格;//例如,这可能计算为:myMap["hammer"] = 10.00

  4. 当你想使用这个值时,简单地给 map 你是关键。

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

关于c++ - (C++) - 将字符串与从文件中读取的值相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21512741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com