【问题标题】:getline() keeps taking the same line as input after a reading a few linesgetline() 在读取几行后继续使用与输入相同的行
【发布时间】:2020-07-31 09:17:07
【问题描述】:

我试图从 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 之后一直重复相同的值。

【问题讨论】:

  • 您的流可能无法以某种方式读取,并且您不是clear()正在流。
  • 在 IO 事务后始终检查流状态。总是。
  • 您的输入文件声称有 43 行数据,但只有 20 行数据。
  • 是的,这就是问题所在。我没有看到下面有更多截断的测试用例。由于我已经为 n 次迭代定义了输入,因此在输入结束后它一直在读取同一行。无论如何,谢谢你们的帮助。

标签: c++ string dictionary stl c++14


【解决方案1】:
//...
for(int i = 0; i < n; ++i) {
    getline(cin, line);
//...

应该是

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

//....

如果你不检查输入操作的结果,各种各样的事情都会出错。

【讨论】:

  • 不,我只是误解了输出。 n 是 43。绝对没有提供 43 行输入。 PEBCAK 暴露的软件错误。
  • @user4581301,呵呵,是的,几乎总是这样。
猜你喜欢
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2020-02-27
相关资源
最近更新 更多