LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   scanf doesn't interrupt flow to read input (https://www.linuxquestions.org/questions/programming-9/scanf-doesnt-interrupt-flow-to-read-input-438367/)

ionuion 04-24-2006 10:55 AM

scanf doesn't interrupt flow to read input
 
hello.
The idea behind my program is to get some numbers to send it asynchronously to a process. The decimals are red from the keyboard.

Code:

#include <stdio.h>

int main(void)
{
        printf("We need integer values. Could you provide us some, please?\n");
        printf("Press Ctrl-C when you have no more to give\n");
        while(1)
        {
                int temp;
                printf("Number? :");
                int ret = scanf("%d", &temp);
                // ferror associated to stdin is 0 at this point 
                if (!ret)
                {
                        printf("This might not be a number.\n");
                        printf("Please try again. What about right now?\n");
                        continue;
                }
                else
                {
                        // Good data. Can send them as useful
                }
        }
}

So, if the user sends an "it", the input shall be ignored, and user prompted for another number. At least that's what I expect. The fact is once an errouneous input is provided, the program behaves as the line containing the call to scanf didn't exist.
I tried to read ferror(stdin). It is 0 in any case.

Any hints will be endlessly appreciated.

Linux 2.6.14.2 PREEMPT i686 GNU/Linux
gcc (GCC) 3.3.6 (Debian 1:3.3.6-13)

Mara 04-24-2006 04:22 PM

That's how scanf() works. In your case, you should read a line as string (using getchar, fgets or read), then use atoi to convert it to a number and that, looking at the result, print the message or deal with the number you have.

ioerror 04-24-2006 05:21 PM

scanf is a function I try to steer clear of.

Quote:

then use atoi to convert it to a number
Better to use strtol, since atoi doesn't detect errors.

ionuion 04-25-2006 07:45 AM

Thank you for your help. I'll look with another pair of eyes at the scanf family.

Regards.


All times are GMT -5. The time now is 07:50 PM.