Search code examples
cinputgetchar

How to remove duplicate output in C program?


I've created a program that takes in a character from user input. It will convert the letter into uppercase and display it to the end user.

However, I am receiving an issue with the output where I get double of "Please enter a character in lower case:" and an extra line below. I'm not quite sure what is causing it but here is the program I have so far:

#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>

// Converts lowercase letter to uppercase

int main()
{
    bool continue_program = true;

    printf("Program Running \n");
    int lower, upper;
    while (continue_program){
        printf("Please enter a character in lower case:");
        printf("\n");
        int lower = getchar();
        if(lower=='q' || lower=='Q'){
            printf("Goodbye \n");
            break;
        } else {
            upper = toupper(lower);
            putchar(upper);
            printf("\n");
        }
    }
    return 0;
}

Output Example:

./a.out
Program Running 
Please enter a character in lower case:
a
A
Please enter a character in lower case:


Please enter a character in lower case:
b
B
Please enter a character in lower case:


Please enter a character in lower case:
p
P
Please enter a character in lower case:


Please enter a character in lower case:
Q
Goodbye 

Solution

  • Just change this:

    int lower, upper;
    

    to:

    char lower, upper;
    

    and this:

    int lower = getchar();
    

    to:

    scanf(" %c", &lower);
         //^ Space which 'eats' remaning '\n' in the buffer