usingnamespace std;
. . .
void
CivvcDateFmt::checkDate(const string &strDate)
{
stringstream sStrDate;
int nDay;
int nMnth;
if (strDate.size() != 8)
{
ExInvalidDateSize EX;
throw EX;
}
sStrDate << strDate.substr(0, 2);
// get the day characters into an int format
sStrDate >> nDay;
if (!sStrDate.eof() || nDay > 31 || nDay < 1)
{
ExInvalidDay EX;
throw EX;
}
// get the month characters into an int format
sStrDate << strDate.substr(2, 2);
sStrDate >> nMnth;
cout << "Month is " << strDate.c_str() << ", " << nMnth << endl;
. . .
The cout line produces the following output: Month is 12, 16711680
I thought the operator>> emptied the stream but obviously it doesn't. How do I clear the stream so that it can be reused? It just seems inefficient creating 2 stringstreams.
use the str function member passing an empty string;
For example:
1 2 3 4 5
stringstream sStrDate;
//put some stuff into the strinstream.
//take some stuff out
//now we want to clear any remaining garbage
sStrDate.str(""); // set stringstream to empty string
That doesn't seem to work. It compiles OK but the operator>> after the reassignment of str() is failing to change the value of nMnth. If I set the value of nMnth to -1, it is still -1 after line 30. I can cout the str() of the stringstream however and it has changed to the newly assigned value. It's just that the operator>> isn't working. I can put another stringstream in the code but it is annoying me now, not understanding what is going on.
I am using Netbeans with gcc 4.3.1 on Solaris 10, if that matters.
It didn't work for me either, then I though Aha - it is a stream and we have emptied it - so it has reched End Of File.
We will need to se the stream GOOD again so that it can be re-used.
here was the test code (basically yours that I tested it with )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
string strDate("12102008"); //I assume that this is what your date format looked like
stringstream sStrDate;
int nDay;
int nMnth;
sStrDate << strDate.substr(0, 2);
// get the day characters into an int format
sStrDate >> nDay;
// get the month characters into an int format
sStrDate.clear(); //reset the stream because we emptied it earlier so it has become EOF
sStrDate << strDate.substr(2,2);
sStrDate >> nMnth; // now it works again
cout << "Month is " << strDate.c_str() << ", " << nMnth << endl;