1

Program:

#include <stdio.h>
int main() {
    char t;
    while(1) {
        t='\0';
        printf("\nExit?(y/n): ");
        scanf("%c", &t);
        if( t=='y' || t=='Y') {
            return 0;
        }
        else
        printf("\nContinuing...");
    }
    return 0;
}

Output:

$ vim Return.c
$ gcc -o Return Return.c
$ ./Return

Exit?(y/n): n

Continuing...
Exit?(y/n):
Continuing...
Exit?(y/n): n

Continuing...
Exit?(y/n):
Continuing...
Exit?(y/n): y
$

after giving 'n' as input, the

Continuing...
Exit?(y/n):

loops for one more time, with out taking input from user. If there any mistake in code , please let me know

DragonX
  • 371
  • 2
  • 6
  • 18

2 Answers2

2

You need to ensure that scanf discards the newline. Try like this:

scanf(" %c", &t);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • just curious to know how it takes new line as input, because '%c' takes only one character as input right? – DragonX Feb 25 '14 at 11:35
  • @DragonX:- The difference between scanf("%c", &c1) and scanf(" %c", &c2) is that the format without the blank reads the next character, even if it is white space, whereas the one with the blank skips white space (including newlines) and reads the next character that is not white space. The "Enter" keypress sends a '\n' to standard input which is what is scanned by your second scanf call. – Rahul Tripathi Feb 25 '14 at 11:38
2

Try giving space in format identifier of scanf statement. try something like

scanf(" %c",&t);
AJ.
  • 4,526
  • 5
  • 29
  • 41
user3152555
  • 195
  • 3
  • 11