c++ - 遍历 file.txt 并更新地图值
问题描述
我试图更新我的地图,因为我迭代了我的 file.txt 我添加了一些“测试代码”来输出我的值,我得到 125.00(这是我想要的)和 100(我不想要)
我不认为我以正确的方式将其插入地图或以正确的方式检索它。因为我添加之前的值是正确的,当我检索它时,它不是正确的方法
if (accountFile.is_open())
{
while (!accountFile.eof())
{
(std::getline(accountFile, accounttemp.user, ',') &&
std::getline(accountFile, accounttemp.trantype, ',') &&
std::getline(accountFile, (accounttemp.bal)));
(std::getline(loginFile, logintemp.user, ',') &&
std::getline(loginFile, (logintemp.pass)));
cout << logintemp.user << endl;
//http://www.cplusplus.com/reference/map/map/find/
// find value given key
it = balances.find(accounttemp.user);
if (it != balances.end())
{
double holder = 0;
if (accounttemp.trantype == "D")
{
holder = std::stod(accounttemp.bal) + std::stod(balances.find(accounttemp.user)->second);
}
if (accounttemp.trantype == "W")
{
holder = std::stod(accounttemp.bal) - std::stod(balances.find(accounttemp.user)->second);
}
stringstream stream;
stream << fixed << setprecision(2) << holder;
string s = stream.str();
accounttemp.bal = s;
//this is were i added some test code to see my output
cout << accounttemp.bal << endl;
balances.insert(pair<string, string>(accounttemp.user, accounttemp.bal));
cout << (balances.find(accounttemp.user)->second) << endl;
enter code here
//out put is 125.00
//out put is 100
}
else
{
balances.insert(std::pair<string, string>(accounttemp.user, (accounttemp.bal)));
}
}
}
cout << "\n";
解决方案
你有:
it = balances.find(accounttemp.user);
if (it != balances.end())
{
balances
仅当包含accounttemp.user
元素时才进入块。然后代码有:
balances.insert(pair<string, string>(accounttemp.user, accounttemp.bal));
它什么都不做,因为地图已经包含一个带有该键的元素。请注意,insert
不会替换现有元素。最多std::multimap
可以插入具有相同键的新元素。但是std::map
什么都不会发生。查看以下文档std::map::insert
:
返回一对由插入元素(或阻止插入的元素)的迭代器和表示插入是否发生的布尔值组成。
我假设它false
为您返回,因为没有插入。
修复:改为更新迭代器:
// instead of:
// balances.insert(pair<string, string>(accounttemp.user, accounttemp.bal));
it->second = accountemp.bal;
推荐阅读
- c++ - “可能未初始化的局部变量”和处理所有可能性的开关
- c - 如何改进 Mersenne Twister vor AVX/SSE?
- javascript - 有条件地显示警报按钮
- php - Display echo on the screen while executing PHP code
- c# - NLog MySql .Net Core 3.0 日志记录未保存到数据库
- excel - 用逗号替换句点以删除句点结束
- reactjs - 使用 map 遍历 JSON 对象以做出反应
- qt - 添加到网格布局的 QWidgets 被放置为就好像它是垂直布局一样
- go - Golang从查询响应中扫描外键
- amazon-web-services - AWS ec2 SSH 超时但仍然可以 ping 它