for loop problem

C

chen_li3

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
 
B

Barry Schwarz

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.
 
C

CBFalconer

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 */
 
B

BartC

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.
 
C

CHAFIK Wassime

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.
 
K

Kenny McCormack

Richard said:
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.
 
G

Guest

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.

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

name three

<snip>
 
K

Kenny McCormack

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.
 
B

Ben Bacarisse

Richard said:
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>
 
C

chen_li3

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.
 
K

Kenny McCormack

BartC said:
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.
 
G

Guest

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>
 
K

Kenny McCormack

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.
 
F

Flash Gordon

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.
 
K

Keith Thompson

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/>.
 
I

Ian Collins

Richard said:
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.
 
C

CBFalconer

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.
 
C

CBFalconer

.... 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.
 
B

Barry Schwarz

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top