Home > Back-end >  how to use scanf with integers or a char in c
how to use scanf with integers or a char in c

Time:10-12

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.

CodePudding user response:

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.

CodePudding user response:

Here's my solution, similar to what Fe2O3 did:

#include <stdio.h> // IO
#include <stdbool.h> // Boolean values

int main(void)
{
    int value; // Integer value
    char ch; // Character value
    bool ended = false; // Loop ended state

    const unsigned int END_CH_LEN = 2; // Length of ending characters array
    char stop_ch[END_CH_LEN] = {'q', 'Q'}; // Ending characters

    for (int i = 0; i < 100; i  )
    {
        // Check loop ended state
        if (ended)
        {
            break;
        }

        // Print prompt
        printf("Enter a number or quitting character (q / Q): ");

        // Try to read integer, and check if the value is integer
        if (scanf("%d", &value) != 1)
        {
            // Read character
            scanf("%c", &ch);

            // Check for ending characters
            for (unsigned int i = 0; i < END_CH_LEN; i  )
            {
                // If match detected
                if (ch == stop_ch[i])
                {
                    // Exit loop
                    ended = true;
                    break;
                }
            }
        }
        else
        {
            // Print integer
            printf("Integer value: %d\n", value);
        }
    }

    return 0;
}

But still, as Fe2O3 previously mentioned, this code is not very scalable; the expected integer is fixed in size, and depending on the return value of scanf to detect non-numerical inputs may break things in the future. If possible, read everything into a string first, then use something like atoi for integer conversion, coupled with dynamic memory allocation for variable-sized strings if needed.

  • Related