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

时间:2016-05-26 04:01:07

标签: c++ getline stringstream istringstream

我需要做什么:我现在有一个行向量,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

1 个答案:

答案 0 :(得分:0)

让我们走过那个删除循环。

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)会在这里提供帮助。