使用 stringstream 和 getline 读取每行的前两个数字

using stringstream and getline to read the first two numbers of each line

我需要做什么:我现在有一个线向量,v[0] 是第一行,依此类推。我想从每一行读取第一个数字作为挑战,从每一行读取第二个数字作为判断,然后应用代码中的条件。我想使用 stringstream 来读取从行中提取的数字。

我的代码现在正在做什么:它只读取每行的第一个数字。所以第一行第一个数字是挑战,第二行第一个数字是裁判,第三行第一个数字是挑战。

    std::vector<string> v;
    string line;
    int i;
    double challenge;
    int judge;

    while (getline(cin, line)) {
        if (line.empty()) {
            break;
        }

        v.push_back(line);
    }

    for (i = 0; i < v.size();i++ ) {
        cin >> v[i];
        std::stringstream ss(v[i]);
        ss << v[i];
        ss >> challenge >> judge;

        if (challenge < 1 || challenge > 5) {
            cout << "bad_difficulty" << endl; //must add the condition or empty
            v.erase(v.begin() + i);
        }

        if (judge != 5 || judge != 7 ) {
            cout << "bad_judges" << endl; //must add the condition or empty
            v.erase(v.begin() + i);
        }

        cout << v[i] << endl;

    }

    return 0;
}

例如:

Input:
 5.1 7 5.4 3.0 9.6 2.9 2.8 2.0 5.4
-3.8 7 2.9 1.1 5.7 7.2 4.8 8.5 3.9
 2.2 5 9.4 4.7 7.3 1.9 5.7 6.0 7.1
 2.4 6 9.2 5.2 1.0 2.9 4.9 7.4 7.9
 2.1 7 7.9 4.9 0.0 7.2 9.1 7.8 6.7 4.3
 3.8 5
 2.0
 4.0 7 2.4 1.9 3.2 8.3 14.8 0.1 9.7
 2.5 7 8.4 -8.0 5.0 6.0 8.0 1.3 3.3
 1.6 -1 9.5 2.5 5.8 7.9 5.5 1.6 7.9

Output should be:
bad_difficulty
bad_difficulty
2.2 5 9.4 4.7 7.3 1.9 5.7 6.0 7.1
bad_judges
2.1 7 7.9 4.9 0.0 7.2 9.1 7.8 6.7 4.3
3.8 5
bad_judges
4.0 7 2.4 1.9 3.2 8.3 14.8 0.1 9.7
2.5 7 8.4 -8.0 5.0 6.0 8.0 1.3 3.3
bad_judges

Current Output:
bad_difficulty
bad_judges
2.2 5 9.4 4.7 7.3 1.9 5.7 6.0 7.1
bad_judges
2.1 7 7.9 4.9 0.0 7.2 9.1 7.8 6.7 4.3
bad_judges
2.0
bad_judges
2.5 7 8.4 -8.0 5.0 6.0 8.0 1.3 3.3
bad_judges
1.6 -1 9.5 2.5 5.8 7.9 5.5 1.6 7.9

让我们来看看删除循环。

i = 0
v[0] contains line 1. 
Line 1 is 5.1 7
challenge > 5, remove 0. The vector shifts up by 1 v[0] now contains line 2
Judge == 7 do not remove 0
increment i

i = 1
v[1] contains line 3. Line 2 has been skipped
Line 3 is 2.2 5
challenge < 5, do not remove 1. 
Judge is not 5 or 7. remove 1. The vector shifts up by 1 v[1] now contains line 4
increment i

i = 2
v[2] contains line 5. Line 4 has been skipped
Line 5 is 2.1 7
challenge < 5, do not remove 2. 
Judge is 7. do not remove 2. 
increment i

i = 3
v[3] contains line 6. 
Line 6 is 3.8 5
challenge < 5, do not remove 3. 
Judge is 5. do not remove 3. 
increment i

i = 3
v[3] contains line 7. 
Line 7 is  2.0
challenge < 5, do not remove 3. 
Judge is UNDEFINED! PANIC! PANIC! Crom only knows what happens.
increment i

总之,这里的基本模式应该很清楚了。当您从 vector 中删除一个元素时,所有后续元素都会向上移动。解决方案:删除元素时,不要递增ielse声明将为您解决这个问题。

接下来,因为有两个单独的 if 语句,所以有可能两个条件都为真,并且 v[i] 将被删除两次。有很多方法可以解决这个问题。 Manthan Tilva 使用 continue 的解决方案简单有效,但这可以使用 else if 或将两个测试滚动到相同的 if.

来更明显地处理

第三,使用未从流中读取的值是未定义的。并且不应使用。丢弃该行,无需进一步查看。 if (ss >> challenge >> judge) 会在这里提供帮助。