Cant make single char in a loop.

Discussion in 'C++' started by mmondal71, May 30, 2010.

  1. mmondal71

    mmondal71 New Member

    Joined:
    May 25, 2010
    Messages:
    19
    Likes Received:
    0
    Trophy Points:
    0
    Hello.

    So I've been doing some C today... and wondering how the heck do I get a single char in a loop? I've used getchar and scanf, they both read my newline and skip prompt on 2nd iteration.
     
  2. spoddar66

    spoddar66 New Member

    Joined:
    May 25, 2010
    Messages:
    23
    Likes Received:
    0
    Trophy Points:
    0
    getchar() should work.

    Show us the code and the input.
     
  3. mmondal71

    mmondal71 New Member

    Joined:
    May 25, 2010
    Messages:
    19
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    #include <stdio.h>
     
    main()
    {
            char c;
     
            while(1)
            {
                    printf("Enter a char: ");
                    c = getchar();
                    printf("%d\n", c);
            }
    }
     
  4. singh_r85

    singh_r85 New Member

    Joined:
    May 25, 2010
    Messages:
    19
    Likes Received:
    0
    Trophy Points:
    0
    Its doing exactly the correct thing getting one character at a time.
    The problem is that you have two sources going to the same device.

    Keyboard input is going to terminal.
    Output from your program is also going to the terminal.

    Simple solution:

    Run the command in one terminal and look at the output of the program in another terminal.

    How:
    Execute program and output to a file:
    ./a.out > PLOP

    tail the file from another terminal

    tail -f PLOP

    PS. You need the -f. It makes tail wait for more input to the file.
     
  5. mmondal71

    mmondal71 New Member

    Joined:
    May 25, 2010
    Messages:
    19
    Likes Received:
    0
    Trophy Points:
    0
    Re: Properly get a single character.
    « Reply #6 on: September 17, 2008, 08:38:32 AM »

    Quote from: myork on September 17, 2008, 08:14:38 AM
    The problem is that you have two sources going to the same device.

    Are you sure?

    I think the problem is the newline stays in buffer, and is read up on next getchar() call.

    I think reading the stream until newline is a simpler solution:

    Code:
    
    int myGetChar()
    {
            int c, dummy;
     
            c = dummy = getchar();
            while(dummy != '\n' && dummy != EOF)
                    dummy = getchar();
     
            return c;
    }
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice