使用 cin 读取逗号分隔的整数对 (x,y) 和任意空格



我正在做一个学校项目,我有点卡住了。如果整数使用以下任何格式cin(因此我输入数字或可以从命令提示符管道输入(,我需要获取输入 SETS:

3,4

2,7

7,1

或选项 2,

3,4 2,7

7,1

或选项 3,

3,4 2,7 7,1

,之后也可能有一个空格,如3, 4 2, 7 7, 1

使用此信息,我必须将集合的第一个数字放入 1 个向量中,将第二个数字(在,之后(放入第二个向量中。

目前,我在下面拥有的内容几乎完全符合我需要它要做的事情,但是当使用选项 2 或 3 从文件中读取时,当std::stoi()到达一个空格时,我得到一个调试错误(abort(( 已被调用(

我尝试过使用字符串流,但我似乎无法正确使用它来满足我的需要。

我该怎么做才能解决这个问题?

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main() {
    string input;
    // Create the 2 vectors
    vector<int> inputVector;
    vector<int> inputVector2;
    // Read until end of file OR ^Z
    while (cin >> input) {
        
        // Grab the first digit, use stoi to turn it into an int
        inputVector.push_back(stoi(input));
        // Use substr and find to find the second string and turn it into a string as well.
        inputVector2.push_back(stoi(input.substr(input.find(',') + 1, input.length())));
    }
    // Print out both of the vectors to see if they were filled correctly...
    cout << "Vector 1 Contains..." << endl;
    for ( int i = 0; i < inputVector.size(); i++) {
        cout << inputVector[i] << ", ";
    }
    cout << endl;
    cout << endl << "Vector 2 Contains..." << endl;
    for ( int i = 0; i < inputVector2.size(); i++) {
        cout << inputVector2[i] << ", ";
    }
    cout << endl;
}

cin已经忽略了空格,所以我们也需要忽略逗号。最简单的方法是将逗号存储在未使用的char中:

int a, b;
char comma;
cin >> a >> comma >> b;

这将解析任何元素之间带有可选空格的单个#, #

然后,要读取一堆这样的逗号分隔值,您可以执行以下操作:

int a, b;
char comma;
while (cin >> a >> comma >> b) {
    inputVector.push_back(a);
    inputVector2.push_back(b);
}

但是,您的两个向量最好替换为单个pair<int, int>向量:

#include <utility> // for std::pair
...
vector<pair<int, int>> inputVector;
...
while (cin >> a >> comma >> b) {
    inputVector.push_back(pair<int, int>{ a, b });
}

演示

最新更新