C++ 使用cin读取带有任意空格的逗号分隔整数对(x,y)
我正在做一个学校的项目,我有点卡住了。如果整数使用C++ 使用cin读取带有任意空格的逗号分隔整数对(x,y),c++,c++11,C++,C++11,我正在做一个学校的项目,我有点卡住了。如果整数使用cin(因此我可以键入数字或从命令提示符输入),我需要以以下任何格式获取输入集: 3,4 2,7 7,1 或选择2 3,4,2,7 7,1 或选择3 3,4 2,7,1 ,后面可能还有一个空格,比如3,4,2,7,1 使用此信息,我必须将集合的第一个数字放入1向量,将第二个数字(在,之后)放入第二个向量 目前,我在下面所做的几乎正是我需要它做的,但是当使用选项2或3读取文件时,当std::stoi()到达一个空格时,我得到一个调试错误(abort
cin
(因此我可以键入数字或从命令提示符输入),我需要以以下任何格式获取输入集:
3,4
2,7
7,1
或选择2
3,4,2,7
7,1
或选择3
3,4 2,7,1
,
后面可能还有一个空格,比如3,4,2,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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
字符串输入;
//创建两个向量
向量输入向量;
向量输入向量2;
//一直读取到文件或^Z结束
同时(cin>>输入){
//抓取第一个数字,使用stoi将其转换为整数
inputVector.push_back(stoi(输入));
//使用substr和find查找第二个字符串,并将其转换为字符串。
inputVector2.push_back(stoi(input.substr(input.find(',)+1,input.length()));
}
//打印出两个向量,看看它们是否正确填充。。。
coutcin
已经忽略了空格,所以我们也需要忽略逗号。最简单的方法是将逗号存储在未使用的字符中:
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);
}
但是,最好将两个向量替换为对的单个向量
:
#包含//用于std::pair
...
向量输入向量;
...
while(cin>>a>>逗号>>b){
push_back(对{a,b});
}
请拿起并阅读。这是。可以是3、7
(带空格),还是必须始终是3,7
且没有空格?@Justin或。只要集合中的一个整数进入vector1,另一个进入vector2,就可以有空格。它应该能够处理任意数量的sets@KappaPride意思是,输入的要求是什么?比如说,如果输入中是3,7
,那么cin>>input
将只读3,
,导致第二个stoi
在空字符串上被调用。非常感谢!我显然是想得太多了,忘记了基本内容!您的解决方案非常有效!
#include <utility> // for std::pair
...
vector<pair<int, int>> inputVector;
...
while (cin >> a >> comma >> b) {
inputVector.push_back(pair<int, int>{ a, b });
}