Я пытаюсь обновить свою карту, когда я перебираю свой файл .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:
Returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place.
Я предполагаю, что он вернул вам false, так как вставки не было.
ИСПРАВИТЬ: вместо этого обновите итератор:
// instead of:
// balances.insert(pair<string, string>(accounttemp.user, accounttemp.bal));
it->second = accountemp.bal;
Спасибо, похоже, это работает для меня
it->second = accountemp.bal;