for loop problem

Discussion in 'C Programming' started by chen_li3@yahoo.com, Apr 13, 2009.

  1. Guest

    Hi all,

    I am new for this forum. I have a question about a for loop in c
    language: I try to get 5 characters one by one from the keyboard and
    print them out. The for loop repeats 5 times BUT only accept 3
    characters(a,b, and c) from keyboard. I wonder if anyone there can
    explains why.

    Thanks,

    Li

    #include <stdio.h>

    main()
    {
    int i;
    int ch;

    for( i = 1; i<= 5; i++ ) {
    printf("%d\n",i);
    ch= getchar();
    putchar(ch);
    }
    }



    output:

    1
    a
    a2

    3
    b
    b4

    5
    c
    c
    , Apr 13, 2009
    #1
    1. Advertising

  2. On Sun, 12 Apr 2009 17:06:39 -0700 (PDT), wrote:

    >Hi all,
    >
    >I am new for this forum. I have a question about a for loop in c
    >language: I try to get 5 characters one by one from the keyboard and
    >print them out. The for loop repeats 5 times BUT only accept 3
    >characters(a,b, and c) from keyboard. I wonder if anyone there can
    >explains why.
    >
    >Thanks,
    >
    >Li
    >
    >#include <stdio.h>
    >
    >main()
    >{
    >int i;
    >int ch;
    >
    >for( i = 1; i<= 5; i++ ) {
    >printf("%d\n",i);
    >ch= getchar();
    >putchar(ch);
    >}
    >}
    >
    >
    >
    >output:
    >
    >1
    >a
    >a2
    >
    >3
    >b
    >b4
    >
    >5
    >c
    >c


    Slowly and very carefully keep a record of exactly which keys you
    pressed to generate this output. Include every key you press, not
    just the letter keys. It should then be obvious what is happening in
    your program.

    If you can execute your program one statement at a time with a
    debugger, you can also see what is happening.

    --
    Remove del for email
    Barry Schwarz, Apr 13, 2009
    #2
    1. Advertising

  3. CBFalconer Guest

    wrote:
    >
    > I am new for this forum. I have a question about a for loop in c
    > language: I try to get 5 characters one by one from the keyboard
    > and print them out. The for loop repeats 5 times BUT only accept
    > 3 characters(a,b, and c) from keyboard. I wonder if anyone there
    > can explains why.


    I have edited your source. I believe it will behave now. Don't
    use tabs in usenet. Do indent properly.
    >
    > #include <stdio.h>
    >
    > int main(void) { /* note main returns int. say it takes no params. */
    > int i;
    > int ch;
    >
    > for (i = 1; i <= 5; i++) {
    > if ('\n' == (ch = getchar())) break; /* exit early on line end */
    > printf("%d ", i);
    > putchar(ch);

    putchar('\n'); /* end line to ensure it is printed */
    > }

    return 0; /* return the program status */
    > }


    --
    [mail]: Chuck F (cbfalconer at maineline dot net)
    [page]: <http://cbfalconer.home.att.net>
    Try the download section.
    CBFalconer, Apr 13, 2009
    #3
  4. BartC Guest

    <> wrote in message
    news:...
    > Hi all,
    >
    > I am new for this forum. I have a question about a for loop in c
    > language: I try to get 5 characters one by one from the keyboard and
    > print them out. The for loop repeats 5 times BUT only accept 3
    > characters(a,b, and c) from keyboard. I wonder if anyone there can
    > explains why.


    > #include <stdio.h>
    >
    > main()
    > {
    > int i;
    > int ch;
    >
    > for( i = 1; i<= 5; i++ ) {
    > printf("%d\n",i);
    > ch= getchar();
    > putchar(ch);
    > }
    > }


    Best in this case to output character codes too, to see what's going on. I
    tried this:

    #include <stdio.h>

    int main(void)
    {
    int i;
    int ch;

    for( i = 1; i<= 5; i++ ) {
    printf("%d: ",i);
    ch= getchar();
    printf("<%c> %d\n",ch,ch);
    }
    }

    Then it's easy to see that:

    (1) Nothing happens until you press Enter
    (2) All the chars you pressed before Enter, are then printed, followed by
    Enter itself, represented by '\n', likely to result in a linefeed and with
    code 10.

    Perhaps you want to read characters one-at-a-time, as they are pressed, that
    will need a special function. On my C I used getch() declared in conio.h.

    --
    Bartc
    BartC, Apr 13, 2009
    #4
  5. On Sun, 12 Apr 2009 17:06:39 -0700, chen_li3 wrote:

    > Hi all,
    >
    > I am new for this forum. I have a question about a for loop in c
    > language: I try to get 5 characters one by one from the keyboard and
    > print them out. The for loop repeats 5 times BUT only accept 3
    > characters(a,b, and c) from keyboard. I wonder if anyone there can
    > explains why.
    >
    > Thanks,
    >
    > Li
    >
    > #include <stdio.h>
    >
    > main()
    > {
    > int i;
    > int ch;
    >
    > for( i = 1; i<= 5; i++ ) {
    > printf("%d\n",i);
    > ch= getchar();
    > putchar(ch);
    > }
    > }
    >
    >
    >
    > output:
    >
    > 1
    > a
    > a2
    >
    > 3
    > b
    > b4
    >
    > 5
    > c
    > c


    hi let's suppose that you have some validating function int isBad(char)
    to see if the typed character suits you or not
    #include <stdio.h>

    main()
    {
    int i;
    int ch;

    for( i = 1; i<= 5; i++ ) {
    ch= getchar();
    if(isBad(ch)){
    i--;//reset
    continue;//be aware that it'll keep looping till it gets 5 good
    chars
    };
    printf("%d\n",i);
    putchar(ch);
    }
    }

    i tried to keep your way of doing things, hope it helps.
    CHAFIK Wassime, Apr 13, 2009
    #5
  6. In article <grv2or$3fm$>,
    Richard <> wrote:
    ....
    >The *only* people I have ever seen use that notation/style were pedantic
    >idiots trying to show off. Pure and simple. It it does not tie in with
    >the vast majority of code "out there" and reads atrociously.


    Quite so.

    >Conventional reading of code is "if variable is of the value then do
    >something".
    >
    >To read "if the value is ..." is simply gibberish in most cases.


    Exactly.

    >It's prancing and showing off. Falconer is as disruptive in his
    >thinking and coding as anyone I have ever seen or worked with in a
    >technical environment.


    It is simply a fiction to believe that any of the CLC "regs" currently
    work in any kind of real-world technical environment. It is an exercise
    in credulity similar to the belief in virgin birth.

    At best, I think some of them are has-beens - that is, they were junior
    programmers at some point in the distant past. At the current time, they
    are simply living on those memories.

    Truly, CLC must be seen as a world onto itself. It does need, nor does
    it have, any reference to a real-world reality.
    Kenny McCormack, Apr 13, 2009
    #6
  7. Guest

    On 13 Apr, 11:11, Richard <> wrote:
    > Barry Schwarz <> writes:


    > > If you can execute your program one statement at a time with a
    > > debugger, you can also see what is happening.

    >
    > Wise advice and something I would reiterate to new programmers : ALWAYS
    > step through your code with a debugger and check the flow is as you
    > would expect.


    not everyone agree you should *always* do this. Scan through some past
    posts on the arguments.

    <snip>

    > In particular many here will tell you to only use "printf".


    name three

    <snip>
    , Apr 13, 2009
    #7
  8. In article <grv355$asj$>,
    Richard <> wrote an excellent summary of the use of
    debuggers - all OT, of course - and, as you well know, that's what
    counts around here:
    ....
    >| You'll be able to find and fix your bugs faster using a symbolic
    >| debugger like GDB. However, this isn't to say that printf() has no use
    >| in debugging. Sometimes it's the best way to go. However, for real code,
    >| a debugger can almost always get the job done orders of magnitude faster
    >| and easier. And using a debugger is always more elegant, and if you
    >| don't care about elegance, you should quit programming on Linux and
    >| start using Visual C++.
    >`----
    >
    >Have fun!


    Yes, but printf() is on-topic. Debuggers aren't.

    That's all that matters, in the CLC grand scheme of things.

    CLC is all about things that are utterly useless, hence, on-topic.
    Kenny McCormack, Apr 13, 2009
    #8
  9. Richard <> writes:

    > Barry Schwarz <> writes:
    >
    >> If you can execute your program one statement at a time with a
    >> debugger, you can also see what is happening.

    >
    > Wise advice and something I would reiterate to new programmers : ALWAYS
    > step through your code with a debugger and check the flow is as you
    > would expect.


    To the OP: I see you have met the only poster here with extreme views
    on debuggers! I feel I must inject a word of caution.

    It is certainly worth learning to use one, but if you are (as seems
    likely) new to programming, you may find it confusing in this specific
    case. The reason is simple. You seem to be having a little trouble
    understanding what is and what is not an input character and how these
    characters are presented to your program by the system (something
    often called line buffering). Adding into this mix another program
    (the debugger itself) that is also reading input from the keyboard can
    confuse things.

    I taught programming to beginners for several years, and even though
    students had learnt to use the debugger before, when they started to
    write interactive programs it sometimes got in the way. For students
    who had a clear picture of how the input system handles line-buffered
    data this was not the case, but for those trying to get a handle on
    that the debugger just complicated the picture.

    <big snip>

    --
    Ben.
    Ben Bacarisse, Apr 13, 2009
    #9
  10. Guest

    On 13 Apr, 04:43, "BartC" <> wrote:
    >
    > Perhaps you want to read characters one-at-a-time, as they are pressed, that
    > will need a special function. On my C I used getch() declared in conio.h.

    Hi all,

    Thanks for all the discussion.
    I think I don't know how getchar() behaves: If I want to use getchar
    (), I need to feed the program with all the letters at once as'abcde'.
    And the program will print them out. But this behavior is not what I
    what: I need do the program run interactively. And I think getch()
    (suggested by BartC) might provide me the solution.
    , Apr 13, 2009
    #10
  11. In article <bXCEl.12532$>,
    BartC <> wrote:
    ....
    >Perhaps you want to read characters one-at-a-time, as they are pressed, that
    >will need a special function. On my C I used getch() declared in conio.h.


    Oh, come now. Everybody here swears that getch() is not C.
    So, you can't possibly have a "getch()" in "my C" (or "your C").
    Or in anything, from C to shining C...

    You are probaly using a language called X&^45jhasC87sdf.
    For all we know, that has a "getch()" function. But of course, we can't
    discuss it here.

    But, Pascal and dirty underwear? Always on-topic.
    Kenny McCormack, Apr 13, 2009
    #11
  12. Guest

    On 13 Apr, 14:36, (Kenny McCormack) wrote:
    > In article <bXCEl.12532$>,BartC <> wrote:


    > >Perhaps you want to read characters one-at-a-time, as they are pressed, that
    > >will need a special function. On my C I used getch() declared in conio.h..

    >
    > Oh, come now.  Everybody here swears that getch() is not C.
    > So, you can't possibly have a "getch()" in "my C" (or "your C").
    > Or in anything, from C to shining C...


    Kenny is a troll and likes to post misleading stuff to confuse newbies
    and disrupt the group. But here there is a grain of truth in what he
    says.
    He isgiving a distorted version of what many regulars say about getch
    ().

    getchar() is not defined by the C language standard ("getch() is not
    C").
    The header conio.h is notdefined by the C language standard (I think
    it's
    a Microsoft-ism).

    But sometimes a program needs to do what you want in which case you
    will
    have to use non-standard extensions. Try not use such extensions
    without
    a good reason, confine them to a small part of your code (eg. wrap
    them in a little library) so they can be easily found and changed.

    For instance you might have to do something different if you try to
    do the same thing on Linux.

    <snip>
    , Apr 13, 2009
    #12
  13. In article <>,
    <> wrote:
    >On 13 Apr, 14:36, (Kenny McCormack) wrote:
    >> In article <bXCEl.12532$>,BartC

    ><> wrote:
    >
    >> >Perhaps you want to read characters one-at-a-time, as they are pressed, that
    >> >will need a special function. On my C I used getch() declared in conio.h.

    >>
    >> Oh, come now.  Everybody here swears that getch() is not C.
    >> So, you can't possibly have a "getch()" in "my C" (or "your C").
    >> Or in anything, from C to shining C...

    >
    >He isgiving a distorted version of what many regulars say about getch
    >().


    Distorted? How so?

    I think it is chapter and verse of what the regs say (and claim to believe).

    >getchar() is not defined by the C language standard ("getch() is not
    >C").


    Quite so.

    Sorry, but it is not C. It might be some other language, but it is not C.
    Kenny McCormack, Apr 13, 2009
    #13
  14. Flash Gordon Guest

    wrote:
    > On 13 Apr, 04:43, "BartC" <> wrote:
    >> Perhaps you want to read characters one-at-a-time, as they are pressed, that
    >> will need a special function. On my C I used getch() declared in conio.h.

    > Hi all,
    >
    > Thanks for all the discussion.
    > I think I don't know how getchar() behaves: If I want to use getchar
    > (), I need to feed the program with all the letters at once as'abcde'.
    > And the program will print them out. But this behavior is not what I
    > what: I need do the program run interactively. And I think getch()
    > (suggested by BartC) might provide me the solution.


    getch() is non-portable and not available on all relatively common
    implementations. conio.h is also non-portable and I personally know of
    two different versions with different contents, I suspect there are
    other versions as well.

    Of course, doing what Chen now says he wants requires a non-portable
    solution, but for the best solution he needs to ask on a group dedicated
    to his platform.
    --
    Flash Gordon
    Flash Gordon, Apr 13, 2009
    #14
  15. writes:
    > On 13 Apr, 04:43, "BartC" <> wrote:
    >>
    >> Perhaps you want to read characters one-at-a-time, as they are pressed, that
    >> will need a special function. On my C I used getch() declared in conio.h.

    >
    > Thanks for all the discussion.
    > I think I don't know how getchar() behaves: If I want to use getchar
    > (), I need to feed the program with all the letters at once as'abcde'.
    > And the program will print them out. But this behavior is not what I
    > what: I need do the program run interactively. And I think getch()
    > (suggested by BartC) might provide me the solution.


    The issue you're running into is that standard input is typically
    line-buffered. This means that the system saves up the characters you
    type and doesn't let your program see them until you press return; at
    that point, all the characters, including the new-line, are presented
    to your program at once.

    There's no standard way to read a single character without buffering.
    There are various non-standard ways to do things like this on most,
    but not all, systems. See section 19 of the comp.lang.c FAQ,
    <http://www.c-faq.com/>.

    --
    Keith Thompson (The_Other_Keith) <http://www.ghoti.net/~kst>
    Nokia
    "We must do something. This is something. Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
    Keith Thompson, Apr 13, 2009
    #15
  16. On 13 Apr 2009 at 15:04, wrote:
    > getchar() is not defined by the C language standard


    You are mistaken.

    7.19.7.6: "The getchar function is equivalent to getc with the argument
    stdin."
    Antoninus Twink, Apr 13, 2009
    #16
  17. Ian Collins Guest

    Richard wrote:
    > Barry Schwarz <> writes:
    >
    >> If you can execute your program one statement at a time with a
    >> debugger, you can also see what is happening.

    >
    > Wise advice and something I would reiterate to new programmers : ALWAYS
    > step through your code with a debugger and check the flow is as you
    > would expect.


    Or for a more professional and repeatable approach, use unit tests.
    Better yet, code test first.

    --
    Ian Collins
    Ian Collins, Apr 13, 2009
    #17
  18. CBFalconer Guest

    wrote:
    > "BartC" <> wrote:
    >>
    >> Perhaps you want to read characters one-at-a-time, as they are
    >> pressed, that will need a special function. On my C I used
    >> getch() declared in conio.h.

    >
    > I think I don't know how getchar() behaves: If I want to use
    > getchar (), I need to feed the program with all the letters at
    > once as'abcde'. And the program will print them out. But this
    > behavior is not what I what: I need do the program run
    > interactively. And I think getch() (suggested by BartC) might
    > provide me the solution.


    Don't do that. getch() is not standard, may not do what his
    version did, etc. The normal input sequence is quite simple:

    The input system receives chars and stores them until a newline
    ('\n') is received. This is normally the result of pressing
    'enter' or <carriage return> on your terminal.

    After that getchar returns the entered chars, one per call,
    advancing one at a time. The last char returned is a '\n'. After
    that another getchar will cause the input system to resume at the
    start of the previous paragraph.

    During this the input line is 'editable', meaning that backspace
    cancels the last char, some char (varies with system) cancels the
    whole line, etc. Once the '\n' has been entered the line is
    complete, and no longer input editable.

    Some systems have provisions to alter this default mechanism.

    --
    [mail]: Chuck F (cbfalconer at maineline dot net)
    [page]: <http://cbfalconer.home.att.net>
    Try the download section.
    CBFalconer, Apr 14, 2009
    #18
  19. CBFalconer Guest

    wrote:
    >

    .... snip ...
    >
    > Kenny is a troll and likes to post misleading stuff to confuse
    > newbies and disrupt the group. But here there is a grain of truth
    > in what he says. He is giving a distorted version of what many
    > regulars say about getch().
    >
    > getchar() is not defined by the C language standard ("getch() is
    > not C"). The header conio.h is notdefined by the C language
    > standard (I think it's a Microsoft-ism).


    I think you mistyped getchar when you meant getch. getchar is
    completely standard. So is getc. Note that these return an int,
    not a char.

    --
    [mail]: Chuck F (cbfalconer at maineline dot net)
    [page]: <http://cbfalconer.home.att.net>
    Try the download section.
    CBFalconer, Apr 14, 2009
    #19
  20. On Mon, 13 Apr 2009 06:22:39 -0700 (PDT), wrote:

    >On 13 Apr, 04:43, "BartC" <> wrote:
    >>
    >> Perhaps you want to read characters one-at-a-time, as they are pressed, that
    >> will need a special function. On my C I used getch() declared in conio.h.

    >Hi all,
    >
    >Thanks for all the discussion.
    >I think I don't know how getchar() behaves: If I want to use getchar
    >(), I need to feed the program with all the letters at once as'abcde'.
    >And the program will print them out. But this behavior is not what I
    >what: I need do the program run interactively. And I think getch()
    >(suggested by BartC) might provide me the solution.


    If yo want the code to be interactive, then write it so that it
    process both the character of interest and the '\n' that will follow
    when the user presses Enter. If you are really ambitions, you could
    also deal with the case where the user types more than one character
    before pressing Enter. If you look at the archives, this has been
    discussed repeatedly.

    --
    Remove del for email
    Barry Schwarz, Apr 14, 2009
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?VGltOjouLg==?=

    Loop the loop...

    =?Utf-8?B?VGltOjouLg==?=, Feb 16, 2005, in forum: ASP .Net
    Replies:
    2
    Views:
    1,370
    Karl Seguin
    Feb 16, 2005
  2. Steven

    while loop in a while loop

    Steven, Mar 24, 2005, in forum: Java
    Replies:
    5
    Views:
    2,216
    Tim Slattery
    Mar 30, 2005
  3. -
    Replies:
    12
    Views:
    677
    Remon van Vliet
    Jun 15, 2005
  4. Byte
    Replies:
    4
    Views:
    405
  5. Isaac Won
    Replies:
    9
    Views:
    352
    Ulrich Eckhardt
    Mar 4, 2013
Loading...

Share This Page