0

I am new to C. I would like to make this code work to exit the while loop when the user introduces the letters f or F.

#include <stdio.h> /*Imported to print in our screen and to input values.*/
#include <conio.h> /*Imported to use the function _clrscre to clear the screen*/
#include <stdlib.h> /*imported because we want to use the sleep function*/

void main()
{

    char inputChar;  
    do
    {

        _clrscr();
        printf("*****************\n*** Main menu ***\n*****************\n\n");

        /*clear buffer and create a variable as a placeholder for the input character the user will input*/
        fflush(stdin);
        scanf("%c",&inputChar);

    }
    while ((inputChar != 'F') || (inputChar != 'f'));

    _clrscr();
    printf("End of the program!\n");
    _sleep(1);
    printf("Bye, user!\n");
    _sleep(2);

The line while ((inputChar != 'F') || (inputChar != 'f')); should make the program to exit the while loop once any of these two letters are introduced by the user. However, it doesn't.

If I replaced the aforementioned line by while (inputChar != 'F'), then the program would work properly exiting the while loop, but only when a capitalized F is introduced by the user (I want the two cases to be covered using this syntax, not only one... and I do not want to use switch case statements).

Any ideas? I believe the problem goes with scanf function and/or its formatting or maybe the boolean expression, but I am rather unsure where the problem is at.

Thank you all!

blackcub3s
  • 189
  • 1
  • 4
  • 5
    Your logic is incorrect. It is *always* the case that either `inputChar != 'F'` or `inputChar != 'f'` is true. It appears that you want the `&&` operator, not `||`. – John Bollinger Dec 10 '18 at 16:03
  • 3
    Note also that `fflush(stdin)` is [explicitly undefined behavior](https://stackoverflow.com/questions/18170410/what-is-the-use-of-fflushstdin-in-c-programming). Don't use it if you want portable code. – Andrew Henle Dec 10 '18 at 16:09
  • 2
    @AndrewHenle I'd say don't use it at all under any circumstance. – klutt Dec 10 '18 at 16:12
  • 1
    Also: `scanf()` without checking return value. Borderline acceptable with `%c`, but generally speaking a very bad habit. – DevSolar Dec 10 '18 at 16:22

1 Answers1

1

You should use && instead of ||.

while ((inputChar != 'F') && (inputChar != 'f'));
Bodo
  • 9,287
  • 1
  • 13
  • 29