-1

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;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Dawsey
  • 3
  • 3

2 Answers2

2

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;
}
dbush
  • 205,898
  • 23
  • 218
  • 273
1
#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.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75