Thread: Good afternoon, I encountered some error when using getchar() and putchar(), pls help

  1. #1
    Registered User
    Join Date
    Jun 2016
    Location
    Malaysia
    Posts
    1

    Question Good afternoon, I encountered some error when using getchar() and putchar(), pls help

    This is my code.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    main()
    {
        char firstchar, secondchar, thirdchar;
        
        printf("Enter 1st character > ");
        firstchar = getchar();
        printf("\n");
        fflush(stdin);
    
        printf("Enter 2nd character > ");
        secondchar = getchar();
        printf("\n");
        fflush(stdin);
    
        printf("Enter 3rd character > ");
        thirdchar = getchar();
        printf("\n");
        fflush(stdin);
    
        printf("You have entered: ");
        putchar(firstchar);
        putchar(secondchar);
        putchar(thirdchar);
        system("pause");
        return 0;
    }

    And this is my output:
    Code:
    Enter 1st character > A
    
    Enter 2nd character >
    Enter 3rd character > B
    
    You have entered: A
    BPress any key to continue . . .
    As you see, I only able to enter 2 value, even I use fflush(stdin) before reading others character.
    P.S. I using Microsoft Visual Studio 2015 to compile.
    Last edited by Chek Wei; 06-17-2016 at 11:17 PM. Reason: To provide more info

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Don't define main like that, FAQ > main() / void main() / int main() / int main(void) / int main(int argc, char *argv[]) - Cprogramming.com

    Don't use "fflush(sdtin);", FAQ > Why fflush(stdin) is wrong - Cprogramming.com

    Your problem is that "getchar()" returns all the characters you typed, and one of them is the newline character( it's entered when you press Return/Enter ). If you want to ignore those whitespace character, you can use scanf, like this:
    Code:
    scanf(" %c", &firstchar);
    note the extra space before the percent sign, that's important as it tells scanf to ignore all whitespace characters.
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getchar() and putchar(c)
    By an96 in forum C Programming
    Replies: 5
    Last Post: 06-13-2015, 04:21 PM
  2. getchar() and putchar()
    By kawaikx15 in forum C Programming
    Replies: 5
    Last Post: 04-13-2011, 11:02 AM
  3. getchar putchar
    By chess2009 in forum C Programming
    Replies: 7
    Last Post: 03-06-2011, 02:44 AM
  4. need help please! getchar, putchar, etc.
    By sue in forum C Programming
    Replies: 1
    Last Post: 03-21-2003, 08:40 PM

Tags for this Thread