Я пытался решить эту проблему из Hackerrank https://www.hackerrank.com/challenges/cpp-maps/problem, но я получаю этот неожиданный вывод из-за того, что getline()
читает один и тот же ввод снова и снова. Вот мой код:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <map>
using namespace std;
int main() {
int n, type, mark;
string line, name;
map<string, int> stud;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for(int i = 0; i < n; ++i) {
getline(cin, line);
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
stringstream line2(line);
line2 >> type >> name;
//cout << "String "<< line << "\n";
if(type == 1) {
line2 >> mark;
auto itr = stud.find(name);
if(itr == stud.end()) {
stud[name] = mark;
}
else {
itr->second = itr->second + mark;
}
}
else if(type == 2) {
stud[name] = 0;
}
else {
auto itr = stud.find(name);
if(itr != stud.end()) {
cout << itr->second << "\n";
}
}
}
return 0;
}
Мой ввод
43
1 tmni 783
1 efukng 259
1 tmni 23
1 wibzw 987
1 pjju 178
1 wibzw 255
2 bpgwa
3 efukng
1 egkjsb 100
3 wibzw
3 egkjsb
1 efukng 128
3 egkjsb
2 tmni
1 tmni 12
3 wibzw
3 efukng
1 egkjsb 10
3 pjju
Мой вывод
259
1242
100
100
1242
387 //works fine till here
178 //Problem starts from here
178
178
178
178
178
178
178
178
178
178
178
178
178
178
178
178
178
178
178
178
178
178
178
178
Как видите, до 387 он работает нормально, но продолжает повторяться то же значение после 178.