0
void main () {
    char f;
   do {
        scanf("%c",&f);// input a  character
        printf("%c",f);//output a  character

   }while(f=='y');
}

any value is going to end the program even if y put is end the program can anyone explain the reason on this program I am stuck at this ..

2 Answers2

1

Other than the void main() (the return value of main should be int) and the failure to check the value returned by scanf (if scanf returns 0 and does not assign a value to f, then attempting to read a value from the uninitialized f is undefined behavior), your program works just fine:

$ echo yyyyyabcd | ./a.out; echo
yyyyya

However, if you are entering data interactively, you may be entering the input stream y\ny\n (hitting enter/return after each y), and the program is terminating when it sees the first newline.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
1

That's because when scanf gets executed again, it is reading a white space character left in the input stream from the previous input you type.

The simplest solution is to include a whitespace character before the %c conversion specifier. Example:

scanf(" %c",&f);// input a  character

This tells scanf to skip leading whitespace.

FSchieber
  • 26
  • 1
  • 6