简体   繁体   中英

getline() keeps taking the same line as input after a reading a few lines

I tried to solve this problem from Hackerrank https://www.hackerrank.com/challenges/cpp-maps/problem , but I keep getting this unexpected output due to getline() reading the same input over and over. Here is my code:

#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;
}

My Input

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

My Output

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

As you can see, it works fine till 387, but keeps repeating the same value after 178.

//...
for(int i = 0; i < n; ++i) {
    getline(cin, line);
//...

Should be

//...
int i = 0;
while(getline(cin, line) && i < n){
    i++;

//....

If you don't check the result of the input operation all sorts of things can go wrong.

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