-2

This is a problem in C. The program Control flow is not as expected. It ask to enter the character in but fail to ask to enter character x.

int foo();

int main(int argc, const char * argv[]) {

    foo();
    return 0;
}



int foo(){

    char in;
    char x;
    printf("Do you wanna party \n");


    if((in = getchar()) == 'y')
        printf("Go Sleep!, I was kidding\n");
    else
        printf("Oh! you are so boaring..\n");


    printf("\nOk, Another Question\n");
    printf("Wanna Go to Sleep\n");


    if((x = getchar()) == 'y')
        printf("ok lets go, Sleepy Head\n");
    else
        printf("No, lets go\n");


    return 0;
}
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • 1
    Are you handling the newline correctly? Recall that most terminals only send input on receipt of a newline, which will appear in `getchar`'s input. – nneonneo Dec 16 '14 at 20:10
  • 1
    Its spelled "boring" BTW. You can also reuse the variable `in` you dont need to declare a second `x` to handle input. – user1231232141214124 Dec 16 '14 at 20:12
  • @nneonneo Do you wanna party in = y Go Sleep!, I was kidding After this no input is asked by program. The following output is displayed Ok, Another Question Wanna Go to Sleep No, lets go Program ended with exit code: 0 This is the output I got when I run the program – Suraj harikrishan Dec 16 '14 at 20:21
  • See related post: http://stackoverflow.com/questions/12544068/clarification-needed-regarding-getchar-and-newline – R Sahu Dec 16 '14 at 20:22
  • @RSahu The question is different. Here x = getchar() doesn't ask for input. The output just displayed. I tried to print the value for x. It's just a blank space – Suraj harikrishan Dec 16 '14 at 20:26
  • @Surajharikrishan, add a `getline()` after the line containing `in = getchar()` and before the line containing `x = getchar()`. – R Sahu Dec 16 '14 at 20:30

1 Answers1

6

To clarify the comments mentioned above, in the process of giving input, you're pressing Y and then pressing ENTER. So, the y is considered as the input to first getchar(), and the ENTER key press [\n] is stored in the input buffer.

On the call to next getchar(), the \n is read, which is considered a perfectly valid input for getchar() and hence your code is not waiting for the next input.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • But even if I use scanf() the answer is same. I also tried the input y y just in case for getchar() but, it didn't work – Suraj harikrishan Dec 16 '14 at 20:35
  • @Surajharikrishan i was expecting this question next. Well, a `\n` is valid for `%c` modifier also. To avoid, write your `scanf()` like `scanf(" %c", &input);`, minding the extra space in `" %c"`. – Sourav Ghosh Dec 16 '14 at 20:38