Re: Duplicate output from stringstream
On Dec 28, 10:21 am, "Aaron J. M." <ajm...@ns.sympatico.ca> wrote:
'M' 1 ',' 0
'L' 0.6 ',' 1.2
...
'L' 2 ',' 1
'L' 1.4 ',' 1.2
',' 1.4 ',' 1.2 // Wrong
Any ideas about what could be causing this?
None of your reads during the last iteration succeed. You are printing
the values of the last iteration.
If I'm not mistaken, the state of the stream is still good, until you
attempt to read past the end of it. This code checks the state of the
stream after every read, which you may already have to do to avoid
reading past badly formatted values:
#include <sstream>
#include <iostream>
using namespace std;
class InputError
{};
template <class T>
void get_value(istream & is, T & value)
{
if (!is || !(is >> value))
{
throw InputError();
}
}
void foo()
{
const char pointList[] =
"M 1,0 L 0.6,1.2 L 0,1 L 0.5,2 L 1,1.75 L 1.5,2 L 2,1 L
1.4,1.2";
double x, y;
char ch;
istringstream stream(pointList);
while (stream)
{
try
{
get_value(stream, ch); // Either 'M' or 'L'
get_value(stream, x);
get_value(stream, ch); // A comma
get_value(stream, y);
cout << ch << ' ' << x << ' ' << y << '\n';
}
catch(const InputError &){
if (!stream.eof()) {
cout << "Something is wrong!\n";
}
}
}
}
int main()
{
foo();
}
Ali
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]