Thread: if/else if statement

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    12

    Post if/else if statement

    i am using an if/else if statement in my code as can be seen below.

    Code:
    void getType()
    {
    char type;
    
    
    printf("\nEnter wind turbine type (v or h):");
    scanf("%c", &type);
    
    
    if (type == 'v' || type == 'V')
    {
    vArea();
    }
    else if (type == 'h' || type == 'H')
    {
    hArea();
    }
    else 
    {
    printf("Invalid input!");
    return getType();
    }
    hArea and vArea are functions that should be used if v or h is entered, however i am having problems with the invalid input section where i get a repetition in the output as seen below. if an invalid input is entered i want the function getType to run again and ask the user for another valid input.

    Enter wind turbine type (v or h):k
    Invalid input!
    Enter wind turbine type (v or h):Invalid input!
    Enter wind turbine type (v or h):


    what in my code needs to be fixed so that the third line is removed and the output will then look like:

    Enter wind turbine type (v or h):k
    Invalid input!
    Enter wind turbine type (v or h):

    cheers

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    The moment you get invalid input you should clean the input stream of any residual characters. I usually do it with something like this:
    Code:
    int c;
    while ((c = getchar()) != '\n' && c != EOF) {
    }
    Oh, and of course, you can also ignore any whitespace characters with scanf by adding a space before the %c in the format string.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Apr 2019
    Posts
    12
    Quote Originally Posted by GReaper View Post
    The moment you get invalid input you should clean the input stream of any residual characters. I usually do it with something like this:
    Code:
    int c;
    while ((c = getchar()) != '\n' && c != EOF) {
    }
    Oh, and of course, you can also ignore any whitespace characters with scanf by adding a space before the %c in the format string.
    cheers it fixed it!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. do/while statement
    By Lukany24 in forum C++ Programming
    Replies: 5
    Last Post: 09-26-2015, 10:18 PM
  2. 'If' Statement inside the Switch statement being ignored.
    By howardbc14 in forum C Programming
    Replies: 4
    Last Post: 04-11-2015, 11:45 AM
  3. Need help on this while statement, thanks!
    By jannr in forum C Programming
    Replies: 2
    Last Post: 07-07-2011, 03:24 AM
  4. Statement inside a statement.
    By JOZZY& Wakko in forum C Programming
    Replies: 15
    Last Post: 11-05-2009, 03:18 PM
  5. Need help with the if statement
    By Sshakey6791 in forum C++ Programming
    Replies: 3
    Last Post: 01-09-2009, 03:26 AM

Tags for this Thread