+-
c – 使用cin读取任意空格的逗号分隔整数对(x,y)
我正在做一个学校项目,我有点卡住了.我需要输入SETS,如果整数使用cin(所以我输入数字或者可以从命令提示符输入),采用以下任何格式:

3,4

2,7

7,1

或选项2,

3,4 2,7

7,1

或选项3,

3,4 2,7 7,1

可能还有一个空格,如3,4 2,4,7 1

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

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

我已经尝试过使用stringstream但我似乎无法正确使用它来满足我的需求.

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

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

但是,您的两个向量将更好地替换为对的单个向量< 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 });
}

DEMO

点击查看更多相关文章

转载注明原文:c – 使用cin读取任意空格的逗号分隔整数对(x,y) - 乐贴网