1

Ok I'm consistently encountering a peculiar issue that I can't get my head around. this loop should return an error if there is a character other than a digit. When I give a character other than a digit, such as A, a or [, it gives me the error message, but it also does when I give a single digit such as say 6 which is what it shouldn't do. The error message doesn't, however, pop up when I give a number such as 03 or 30 that recognises it as 3 or 30 and lets that be used as the encryption key. So what is going wrong with my loop here?

string d = argv[1];  

for (int c = 0, l = strlen(d - 1); c <= l; c++)
    { 
        if ((isdigit(d[1])) == 0 )
        {
            printf("This is an invalid entry\n");
            return 1;
        }
    }

1 Answer 1

2

It's always the problems that hide in plain sight that get us! ;-)

isdigit() is working exactly as expected. If a character is a digit, it returns a non-zero (not necessarily 1, try printing the return value as an int) if true and returns 0 if false. There's no need to use this function in any special way as was suggested.

The problem here appears to be a typo. Look at the line of code:

    if ((isdigit(d[1])) == 0 )

It is always going to check the second digit in the char array d on every pass through the loop. I suspect that, for the array index, this was supposed to use the variable l used to control the loop, not the number 1.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • 1
    ah you're completely right! I've been obsessing over this for hours and it was so simply! all I had to do was change d[1] to d[c] and change the condition in the loop to c <= l - 1. thank you very much for the help! Aug 18, 2016 at 21:44
  • 1
    See how easy it is to overlook something? I read it too fast and saw L when I should have said c! ;-)
    – Cliff B
    Aug 18, 2016 at 22:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .