I am learning C++ at the moment and am working to understand streams. Today I learned this really cool thing, you can split a string stream into multiple floats/integers, like:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
stringstream ss("1 2.2");
int val1; float val2;
ss >> val1 >> val2;
cout << "val1: " << val1 << endl
<< "val2: " << val2;
return 0;
}
Now a problem arises when instead of "1 2.2" as an input string I use "1,2.2", which is similar to what I would get from a csv file. I would like to be able to write something that would take such a csv string and transform it into the same type of stream as in the example above. I imagine it would look something like
ss >> mySpecialPipe >> val1 >> val2;
Now I know mySpecialPipe
should do a few things:
- Take in the input
- Split the input
- Write the input when requested
So I tried to build this:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class MySpecialPipe {
private:
char delimiter;
public:
vector<string> buffer;
MySpecialPipe(char delimeter);
friend istream& operator>> (istream &in, MySpecialPipe &p);
friend istream& operator>> (MySpecialPipe &p, istream &in);
};
MySpecialPipe::MySpecialPipe(char delimeter): delimiter(delimeter) {}
istream& operator>> (istream &in, MySpecialPipe &p)
{
string s;
while (getline(in, s, p.delimiter)) {
p.buffer.push_back(s);
}
return in;
}
istream& operator>> (MySpecialPipe &p, istream &in) {
for (string s: p.buffer) {
// s >> in;
}
p.buffer.clear();
return in;
}
int main() {
MySpecialPipe p = MySpecialPipe(',');
stringstream ss("1,2.2");
stringstream ss2;
ss >> p >> val1 >> val2;
}
As you can see I have uncommented the line s >> in
, because the compiler complains, but essentially that is what I want to do. Is this even possible?
If you got here, thank you for your time, I look forward to your answers.