Suppose I'm running a loop and the loop should continue unless I get a garbage value.
So what will be the terminal condition. How can garbage value be checked in if condition?

4 Years
Discussion Span
Last Post by deceptikon

Then you need to figure out what the heck a "garbage" value is before you can tell the computer how to recognize one. You can't write code to do something you yourself are unable to do manually.


So it's impossible to find out the garbage value as in dynamic arrays on paper?


The word "garbage" is meaningless outside the context of your problem domain. You need to define what it means to your program. For example, if the domain of the program is to read numbers from 0 to 10, then anything that's not a number and any number outside the range of 0-10 constitutes garbage.

So...what input does your program expect, and what input falls outside of that expectation? You want to identify and allow only the expected input and treat everything else as garbage.


Then checking for garbage values is as simple as this:

int value;

if (!(cin >> value)) {
        The stream begins with garbage

    // Restore the stream to a good state

    // Clear the entire line since you don't know where the garbage ends
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

Formatted input will validate the contents of the stream for you, and probably far more completely than if you tried to validate integers manually.

This article has been dead for over six months. Start a new discussion instead.
Be sure to adhere to our posting rules.