Thread: If statement to ask yes/no question

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    3

    If statement to ask yes/no question

    Hi sorry if this has already been asked but I've looked and couldn't find it. I've been working on a program for my university work I want the program to repeat if the user answers yes to a question but the code I have written does not work and I can't see why.
    Code:
      
    char answer = '\0';
    
        printf("Would you like to calculate another price? Y/N: ");
        scanf("%c", &answer);
    
        if ( answer == 'Y' || answer == 'y' )
        {
            mn();
        }
        else
        {
            return 0;
        }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    If you've been using other scanf formats, you typically have to write
    scanf(" %c", &answer); // note leading space
    to skip any whitespace, and thus read the next non-space character.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Also, using an if will only allow you to repeat once per if statement. I suspect you're calling your mn() function recursively to repeat this, which is not a good method, as it can use up all your stack space and crash your program. Use a loop. do while loops work well for user input:
    Code:
    do {
        calculate a price
        print "Repeat?"
        read answer
    } while (answer == 'Y' || answer == 'y');

  4. #4
    Registered User
    Join Date
    Mar 2012
    Posts
    3
    Thank you that worked perfectly

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. if and else statement question
    By elpedoloco in forum C++ Programming
    Replies: 4
    Last Post: 09-30-2011, 02:59 PM
  2. Question about if statement
    By 127.0.0.1 in forum C Programming
    Replies: 2
    Last Post: 03-13-2011, 08:29 AM
  3. A question on what i think is my if statement
    By brian75 in forum C++ Programming
    Replies: 8
    Last Post: 12-17-2008, 06:04 PM
  4. For Statement Question
    By thekautz in forum C++ Programming
    Replies: 6
    Last Post: 11-11-2008, 04:38 PM
  5. Question about if-statement.
    By omnificient in forum C Programming
    Replies: 11
    Last Post: 12-21-2007, 03:54 PM