[Courses] C Programming For Absolute Beginners, Lesson 2: Fun With Printf, Scanf, Puts, and Variables

Jacinta Richardson jarich at perltraining.com.au
Wed Feb 29 06:18:36 UTC 2012


On 29/02/12 16:56, Sachin Divekar wrote:
>
> Then I found a less risky solution to flush input stream buffer.
>
> //    using flush_i() to clear input stream buffer
>
> #include<stdio.h>
> int main()
>        {
>
>        void flush_i(void){
>
>                int c;
>                while (c != '\n' && c != EOF){
>                c = getchar();
>                }
>        }
>
>        int a, b, c;
>        printf("Please enter any number up to three digits:" );
>        scanf("%d", &a);
>
>        flush_i();
>
>        printf("You entered %d. Now enter another number up to three 
> digits:\n", a );
>        scanf("%d", &b);
>
>        c = a + b;
>        printf("%d + %d = %d\n", a, b, c);
>
>        return 0;
> }
>

It's usually considered good form to create functions separately, rather than 
embedding them inside other functions.  To do this we do need one extra line, 
which is where we give the function prototype (header) so that when C is 
compiling the code it knows what that function takes and returns.

    //    using flush_i() to clear input stream buffer

    #include<stdio.h>

    /* our prototype */

    void flush_i(void);

    /* Now our main function */

    int main() {

            int a, b, c;
            printf("Please enter any number up to three digits:" );
            scanf("%d", &a);

            flush_i();

            printf("You entered %d. Now enter another number up to three
    digits:\n", a );
            scanf("%d", &b);

            c = a + b;
            printf("%d + %d = %d\n", a, b, c);

            return 0;
    }

    void flush_i(void){
            int c;
            while (c != '\n' && c != EOF){
                    c = getchar();
           }
    }


> Here flush_i() discards everything upto the next new line in the input stream 
> buffer.
>
> Even if we can discard the wrong input here, flush_i() might be useful 
> somewhere else.
>

Good work.

     J



More information about the Courses mailing list