I'm working on a school project and I'm a little stuck. I need to get input SETS if integers using cin
(so I type in the numbers OR can pipe in from command prompt) in any of the following formats:
3,4
2,7
7,1
OR option 2,
3,4 2,7
7,1
OR option 3,
3,4 2,7 7,1
There might also be a space after the ,
, like 3, 4 2, 7 7, 1
Using this info, I must put the first number of the set into 1 vector and the second number (after the ,
) into the second vector.
Currently, what I have below does almost exactly what I need it to do, however when using option 2 or 3 reading from a file, when std::stoi()
reaches a space, I get a debug error (abort() has been called)
I've tried using stringstream but I can't seem to use it correctly for what I need.
What can I do to fix this?
#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;
}