J
Jason Heyes
I would like to report formatted input operations that fail. To achieve this
I write messages that reflect failed operations to std::cerr. For example,
#include <iostream>
#include <string>
class Foo
{
int a;
int b;
public:
Foo() : a(0), b(0) { }
Foo(int a_, int b_) : a(a_), b(b_) { }
std::istream &read(std::istream &is);
};
std::istream &Foo::read(std::istream &is)
{
int a;
if (!(is >> a))
{
std::cerr << "Failed to read instance of int" << std::endl;
return is;
}
// as you can see, these print statements are a pain to write out
// they also make the code look horrible
// can these be factored out into a separate class or method?
// how?
int b;
if (!(is >> b))
{
std::cerr << "Failed to read instance of int" << std::endl;
return is;
}
*this = Foo(a, b);
return is;
}
inline std::istream &operator>>(std::istream &is, Foo &foo)
{ return foo.read(is); }
int main()
{
std::string s;
if (!(std::cin >> s))
{
std::cerr << "Failed to read instance of std::string" << std::endl;
return 1;
}
Foo foo;
if (!(std::cin >> foo))
{
std::cerr << "Failed to read instance of Foo" << std::endl;
return 1;
}
// what about a quiet version of std::cin >> foo?
// operator>> is already defined to report failures
// what do I do?
return 0;
}
How can I address the issues that are described in comments? Thanks.
I write messages that reflect failed operations to std::cerr. For example,
#include <iostream>
#include <string>
class Foo
{
int a;
int b;
public:
Foo() : a(0), b(0) { }
Foo(int a_, int b_) : a(a_), b(b_) { }
std::istream &read(std::istream &is);
};
std::istream &Foo::read(std::istream &is)
{
int a;
if (!(is >> a))
{
std::cerr << "Failed to read instance of int" << std::endl;
return is;
}
// as you can see, these print statements are a pain to write out
// they also make the code look horrible
// can these be factored out into a separate class or method?
// how?
int b;
if (!(is >> b))
{
std::cerr << "Failed to read instance of int" << std::endl;
return is;
}
*this = Foo(a, b);
return is;
}
inline std::istream &operator>>(std::istream &is, Foo &foo)
{ return foo.read(is); }
int main()
{
std::string s;
if (!(std::cin >> s))
{
std::cerr << "Failed to read instance of std::string" << std::endl;
return 1;
}
Foo foo;
if (!(std::cin >> foo))
{
std::cerr << "Failed to read instance of Foo" << std::endl;
return 1;
}
// what about a quiet version of std::cin >> foo?
// operator>> is already defined to report failures
// what do I do?
return 0;
}
How can I address the issues that are described in comments? Thanks.