Search code examples
cloopscharscanf

how to use scanf with integers or a char in c


Basically I have a simple loop that has a scanf

int main(void){
 int num, i;
  
 for(i=0; i<100; i++){
 printf("enter a number or Q to quit");
 scanf("%d",&num);
 }
}

How can I use scanf with integers to keep the loop going and for the Chars 'Q' and 'q' to stop the loop by setting i to 100.


Solution

  • Can't claim that this will work in all cases, but it seems to work for me.

    int main() {
        int num, i;
        char q;
    
        for( i = 0; i < 100; i++ ) {
            printf("enter a number or Q to quit: ");
            if( scanf("%d",&num) != 1 ) {
                scanf( " %c", &q );
                printf( "picked up %c\n", q );
            }
            printf("number %d\n", num );
    
        }
        return 0;
    }
    
    enter a number or Q to quit: 42
    number 42
    enter a number or Q to quit: 27
    number 27
    enter a number or Q to quit: q
    picked up q
    number 27
    

    It's not very good code... You really should use fgets() and interpret whatever buffer load you get from the user.