Given the input, the easiest way is to check the string token as being the -0
delimiter.
#include <iostream>
#include <sstream>
#include <string>
using std::cin;
using std::cout;
using std::getline;
using std::string;
using std::stringstream;
int main(){
string s,t;
getline(cin, s);
stringstream x(s);
char const* sep = "";
while (x >> t) {
if (t == "-0") {
cout << sep << "<DELIMITER>";
} else {
cout << sep << t;
}
sep = " ";
}
cout << "\n";
}
That gives:
echo '2 -0 1,2 -0' | ./a.out
2 <DELIMITER> 1,2 <DELIMITER>
Update
Storing the values into a std::vector<int>
.
#include <cstddef>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::getline;
using std::ostream;
using std::runtime_error;
using std::size_t;
using std::stoi;
using std::string;
using std::stringstream;
using std::vector;
static auto MakeVecInt(string line) -> vector<int> {
auto result = vector<int>();
auto ss = stringstream(line);
auto value = string{};
while(getline(ss, value, ',')) {
result.push_back(stoi(value));
}
return result;
}
static auto operator<<(ostream& out, vector<int> const& v) -> ostream& {
char const* sep = "";
for (auto i : v) {
out << sep << i;
sep = " ";
}
return out;
}
int main() {
auto line = string{};
getline(cin, line);
auto ss = stringstream(line);
auto count = size_t{};
auto delimiter1 = string{};
auto values = string{};
auto delimiter2 = string{};
if (!(ss >> count >> delimiter1 >> values >> delimiter2))
throw runtime_error("bad input");
if (delimiter1 != "-0" || delimiter2 != "-0")
throw runtime_error("bad input");
auto vec = MakeVecInt(values);
if (count != vec.size())
throw runtime_error("bad input");
cout << vec << "\n";
}
Update
Note in the above code the vector<int>
output routine:
static auto operator<<(ostream& out, vector<int> const& v) -> ostream&
It outputs each element in the vector, with a space between each element. It does not output a space before the first element.