简体   繁体   中英

C - If else if scanf not working

Scanf doesn't work at the else if part. It doesn't read the 'n' character. I can't find the reason. Any suggestion would be appreciated.

int main() {

     int a, i;
     char answer= '\0';

     printf("Give a number: ");
     scanf("%d", &a);

     for(i=1; i<=a; i++) {
        printf("%d\n", i);
     }
     printf("Run again (y/n)? ");
     scanf(" %c", &answer);


     if(answer == 'y' || answer == 'Y' ) {

         printf("Give a number: ");
         scanf("%d", &a);

         for(i=1; i<=a; i++) {
         printf("%d\n", i);

        }
     }

     else if(answer == 'n' || answer == 'N' ) {

     printf("Exiting...\n");
     }

return 0;
}

The problem is you're not using a loop:

int main() {

    int a, i;
    char answer= '\0';

    do {

        printf("Give a number: ");
        scanf("%d", &a);

        for(i=1; i<=a; i++) {
            printf("%d\n", i);
        }
        printf("Run again (y/n)? ");
        scanf(" %c", &answer);

    } while (answer == 'y' || answer == 'Y' );

    printf("Exiting...\n");

    return 0;
}
#include <stdio.h>
char askagain();
int main()
{
     do {
        int a;
        printf("Give a number: ");
        if (getint(&a))
            printnums(a);
     } while (askagain() == 'y');
     return 0;
}
char askagain()
{
    char line[2];
    printf("Again? ");
    fgets(line, 2, stdin);
    return *line;
}
void printnums(int a)
{
    int i;

    for (i = 1; i <= a; ++i)
        printf("%d\n", i);
}
int getint(int *x)
{
    int ret;
    ret = scanf("%d", x);
    flush();

    return ret;
}
void flush()
{
    int c;
    while ((c = getchar()) != '\n')
        ;
}

The flush function indicates how to flush the stdin . Just consuming all the characters until a newline is seen. Dont use fflush(stdin) because that is undefined on input streams.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM