Reading a tag and writing to std::cout.

J

Jason Heyes

I have a function that reads tags. The function prints any failures it
encounters to std::cout.

std::istream &read_tag(std::istream &is, std::string &tag)
{
std::string s;
if (!(is >> s))
{
std::cout << "Failed to read string of tag" << std::endl;
return is;
}

if (!(s == "start" || s == "end"))
{
std::cout << "Failed to read string of tag" << std::endl;
is.setstate(std::ios::failbit);
return is;
}

tag = s;
return is;
}

How do I write a silent version of read_tag that uses read_tag to complete
its task?

std::istream &read_tag_silent(std::istream &is, std::string &tag)
{
/* ? */
}

Any help is appreciated.
 
I

Ioannis Vranos

Jason said:
I have a function that reads tags. The function prints any failures it
encounters to std::cout.

std::istream &read_tag(std::istream &is, std::string &tag)
{
std::string s;
if (!(is >> s))
{
std::cout << "Failed to read string of tag" << std::endl;
return is;
}

if (!(s == "start" || s == "end"))
{
std::cout << "Failed to read string of tag" << std::endl;
is.setstate(std::ios::failbit);
return is;
}

tag = s;
return is;
}

How do I write a silent version of read_tag that uses read_tag to complete
its task?

std::istream &read_tag_silent(std::istream &is, std::string &tag)
{
/* ? */
}


Inherit from istream, define a new operator << and create a new object
jasonCout.
 
J

Jonathan Turkanis

Noah said:
I don't believe you can. Since cout is hard coded into your function
there is no way to alter it without actually closing cout,

There's no such thing as 'closing cout'
but that
might cause some sort of error. You should have implemented it with a
ostream parameter for error output. Then you could pass it a bogus
ostream that doesn't do anything with its input.

You can temporarily set cout's stream buffer to a 'null' buffer which discard
it's output.

Jonathan
 

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

Forum statistics

Threads
474,201
Messages
2,571,049
Members
47,652
Latest member
Campbellamy

Latest Threads

Top