0

I have a class that I have been given some error input handling for. It's a class that has been given it's own "extraction" operator and I've been asked to implement the code that I've been given. The problem I'm having is that the code I should use looks similar to this.

try {
    while (some condition)
    {....implemented code....}
} catch (runtime_error& e) {
    cerr << e.what() << endl;
    return 1;
}

The problem I am having compiling this is it doesn't seem to like the "return 1" value it gives me an error of:

invalid initialization of non-const reference of type ‘std::istream& {aka std::basic_istream<char>&}’ from an rvalue of type ‘int’

If I remove the return value it compiles straight but then the program fails to execute once it hits the area where it is trying to do the try statement. As mentioned the code I have there is the above is the example code we are supposed to implement so I assumed straight out of the box it would work. My condition for the while loop was

while (!std::cin.fail())

as I assumed I'd want to keep getting input until it fails for some reason. Why would the return values in this case be causing a problem?

2
  • 1
    You should return an istream &. And I mean the reference, not a variable going out of scope. Commented Apr 18, 2013 at 0:12
  • You can simplify your while loop to just: while (std::cin) - it has same meaning as the above, but 8 characters less to type. Commented Apr 18, 2013 at 0:33

1 Answer 1

1

Psychic debugging indicates:

your enclosing function has a signature of the form

std::istream& func_name(/*parameter list goes here*/)

Hence the compilation error

Sign up to request clarification or add additional context in comments.

4 Comments

Yes it does however shouldn't the try and catch would still be in that method correct? I'm assuming in this instance the 1 is a placeholder and I need to replace it with the istream that I passed to the function then?
@gRnt No the 1 is not a placeholder. Any function that returns a stream referance AFAIK always returns the same istream object and that object is itself a parameter, never a local object.
EDIT: Now looking at the sample output I think the program is supposed to spit out the number 1. As in if I get a particular error then instead of displaying the result it should display the number 1 and then spit out the error through cerr. Not sure how to do this but will keep reading.
I completely misunderstood the task at hand. I will mark this answer as correct purely because what I was asking at the time although horrendously wrong was answered by the person above. I did however manage to work out what I was doing and the original question was waaaay off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.