Shameful

As shameful as it is, I spent a while trying to help Mike with his C++ programs, attempting to read a particular format of characters from stdin.

The problem is that if this program is fed character data, it loops continuously:


bool valid = false;
int num;
while (!valid)
{
    int num_reads = scanf("%02d", &num);
    if (num_reads == 1)
    {
        valid = true;
    }
}


Why? num_reads is 0 and upon reaching scanf for the second time, the buffer is still attempting to read something, but it can't and returns 0.. and so on and so forth.

So what's the solution? Simple. Use sscanf!


int num;
char buffer[1024];
bool valid = false;
while (!valid)
{
    std::cin >> buffer;
    int num_reads = sscanf(buffer,"%d",&num);
    if (num_reads == 1)
    {
        valid = true;
    }
}