gpt4 book ai didi

c++ - 使用 cin 读取带有任意空格的逗号分隔整数对 (x,y)

转载 作者:太空狗 更新时间:2023-10-29 20:35:36 25 4
gpt4 key购买 nike

我正在做一个学校项目,但有点卡住了。如果整数使用 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 个 vector ,将第二个数字(在 , 之后)放入第二个 vector 。

目前,我在下面所做的几乎完全符合我的需要,但是当使用选项 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);
}

但是,您的两个 vector 最好用 pair<int, int> 的单个 vector 代替:

#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),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42126953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com