Link to home
Start Free TrialLog in
Avatar of joellamarie
joellamarie

asked on

Need assisting with program output

If i enter a int, the program end as it should, but if i enter a char, the program does not end properly, goes on and on  " Bad Choice"

{
    char test[255];
    int input;
    char* conversion_end;
    do
    {
         scanf("%255s", test);
         input = (int)strtol(test,&convert_end,10); // *convert_end must be NULL if an integer was entered
         
         if (input <start || input>stop || NULL != *convert_end)
         {
              printf("\t\tBad choice, please try again\n");
         }
    }while(input<start || input>stop);
    return input;
}
Avatar of Infinity08
Infinity08
Flag of Belgium image

What are the values for start and stop ?
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you enter a value that contains a non-numeric 'conversion_end' will point to the first non-numeric encountered and this will cause your code to go into the code that prints bad choice.

http://www.cplusplus.com/reference/clibrary/cstdlib/strtol.html
btw, are you sure that the code you posted is the same that causes the problem ? And are you sure that the input stream is still in a good state ? You can check that with ferror :

        http://www.cplusplus.com/reference/clibrary/cstdio/ferror.html

@evilrix : the problem is that it apparently goes in an infinite loop.
>> the problem is that it apparently goes in an infinite loop.
Well this is, of course, possible depending upon the values of start and stop -- as you've already eluded.
Even then, it shouldn't go in an infinite loop with the code posted, since the scanf reads new data in every iteration. So, it seems that the scanf fails for some reason (which makes that the same string is parsed in each iteration).

Can you check the return value of scanf, joellamarie ? It should be 1.
Avatar of joellamarie
joellamarie

ASKER

If figure the problem out, I used conversion instead of convert  and the program work
>> Even then, it shouldn't go in an infinite loop with the code posted
Hmmm, I didn't read it as infinite loop... I guess that was implicit and I just didn't pick up on that.
Didn't your compiler throw an error because of that ?
@evilrix : I interpreted "goes on and on" as "infinite"
>> I interpreted "goes on and on" as "infinite"
Yeah, I though joellamarie meant if an invalid char was continuously entered. On reflection, your interpretation does make more sense :)