why there is an error when using stringstream?

P

PengYu.UT

Hi,

The following code would output "error". I don't understand why there
is such error. Could you please help me?

Thanks,
Peng

#include <string>
#include <sstream>
#include <iostream>

int main() {
double e, e1;
e = 10;
std::eek:stringstream oss;
oss << e;

std::istringstream iss(oss.str());
iss >> e1;

e = 0;
oss.str("");
oss << e;

iss.str(oss.str());
if(!(iss >> e1))
std::cout << "error" << std::endl;
}
 
M

Michael DOUBEZ

(e-mail address removed) a écrit :
Hi,

The following code would output "error". I don't understand why there
is such error. Could you please help me?

Thanks,
Peng

#include <string>
#include <sstream>
#include <iostream>

int main() {
double e, e1;
e = 10;
std::eek:stringstream oss;
oss << e;

std::istringstream iss(oss.str());
iss >> e1;

Here eofbit is set in iss.
e = 0;
oss.str("");
oss << e;

iss.str(oss.str());

The following fail because you didn't clear iss state thus eofbit is
still set and extraction fails.

insert:
iss.clear();
if(!(iss >> e1))
std::cout << "error" << std::endl;
}

Michael
 
P

PengYu.UT

(e-mail address removed) a écrit :







Here eofbit is set in iss.





The following fail because you didn't clear iss state thus eofbit is
still set and extraction fails.

insert:
iss.clear();


Michael

Do I need to clear for oss?

Thanks,
Peng
 
M

Michael DOUBEZ

(e-mail address removed) a écrit :
Do I need to clear for oss?

No.

I cannot remember when a failbit of badbit would be set on a ostream. It
would happen if the underlying streambuf failed and would be in an
unpredicable state so you'd rather recreate it.

Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top