0

This a simple code to print 6 numbers and then ask if the user want to continue, but in some point the value of my flag to continue changes. Any idea? And does the while at the end of the do-while block only accept one condition?

Here is the code:

void x(){
    int i = 1, cont = 0;
    char flag;

    do{
        if(cont == 6 && (flag != 'n' || flag != 'N')){
            printf("(S/N)");
            scanf("%c", &flag);
            printf("\n :%c \n", flag);
            if(flag == 's' || flag == 'S'){
                cont = 0;
                printf("\n");
            }
        }else{
            printf("%d, ", i);
            i++;
            cont++;
        }
    }while(flag != 'n' || flag != 'N');
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Mac
  • 111
  • 7
  • 14
  • After you enter the `flag` for the first time, you also enter a `\n` character to the stdin buffer. That is causing the problem – 0aslam0 Mar 11 '15 at 05:48
  • possible duplicate of [C Program :Error when reading character from stdin using scanf](http://stackoverflow.com/questions/27436075/c-program-error-when-reading-character-from-stdin-using-scanf) – Santosh A Mar 11 '15 at 05:56
  • You should test `scanf` return value and `break` if it returns `!= 1`. – chqrlie Mar 11 '15 at 08:18

1 Answers1

3

You have to replace

 scanf("%c", &flag);

with

scanf(" %c", &flag);

to avoid scanning the whitespace-family [here, the \n which is stored in input buffer from previous ENTER key press].

Next, you've to rethink the logic. I did not understand the purpose of checking the input agaisnt S. IMHO, its not necessary. If I have understand your purpose correctly, you can re-write the code like below

#include <stdio.h>
#include <stdlib.h>

int main(){
    int i = 1, cont = 0;
    char flag;

    do{
        if(cont == 6 && (flag != 'n' || flag != 'N')){
            printf("(Y/N)");
            scanf(" %c", &flag);               //ignore whilespace-family
            printf("\n :%c \n", flag);
            if(flag == 'y' || flag == 'Y')     // check for Y or y and continue the next set to print
            {
                cont = 0;
                printf("\n");
            }
            else if (flag == 'n' || flag == 'N')   // check for n or N and break out of loop
                break;
            else
                printf("Invalid choice\n");        // ask the input again
        }else{
            printf("%d, ", i);
            i++;
            cont++;
        }
    }while(1);                                     // infinite loop
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261