Reading a key inside a loop

H

hstagni

When i read a key using getchar() inside a loop, the program stops and
wait for a key to be pressed. I actually want the program to continue
its execution until a key is pressed. Look at this sample:
------
while(1=1)
{
printf("oi");
ch=getchar();
if (ch=='q') break;
}

I want the program to print 'hi' forever(something like
"hihihihihihihihihihihihihi" until 'q' is pressed. Is there an easy
way to do this?
(this program actually stop the printing of 'hi' and waits for a key
to be pressed. I dont want this!)


Sorry about the bad english
 
M

mark_bluemel

When i read a key using getchar() inside a loop, the program stops and
wait for a key to be pressed. I actually want the program to continue
its execution until a key is pressed.

FAQ 19.1 - see http://c-faq.com/ or more particularly http://c-faq.com/osdep/cbreak.html
Look at this sample:

What's wrong with for(;;) or while(1) ?
{
printf("oi");
ch=getchar();
if (ch=='q') break;

}

I want the program to print 'hi' forever

Well it won't do so when you've coded "oi"...
 
A

Army1987

hstagni said:
When i read a key using getchar() inside a loop, the program stops and
wait for a key to be pressed. I actually want the program to continue
its execution until a key is pressed. Look at this sample:
------
while(1=1)
{
printf("oi");
ch=getchar();
if (ch=='q') break;
}

I want the program to print 'hi' forever(something like
"hihihihihihihihihihihihihi" until 'q' is pressed. Is there an easy
way to do this?
(this program actually stop the printing of 'hi' and waits for a key
to be pressed. I dont want this!)

Why do you want that?
Anyway, there is no portable way of doing that. It depends on what system
you're working on.
http://c-faq.com/osdep/cbreak.html
 
A

Army1987

hstagni said:
while(1=1)

This tries to assign 1 to 1. But you can't assign to a decimal constant.
You meant while (1==1), or, as mark_bluemel pointed out, while (1).
 
M

Mark McIntyre

I want the program to print 'hi' forever(something like
"hihihihihihihihihihihihihi" until 'q' is pressed. Is there an easy
way to do this?

This is a FAQ. - 19.1

Quick answer: you can't, C's standard IO functions all require you to
press a key to tell the programme you've finished typing.
Longer answer: your OS probably has a lower level function which can
do this. You may need to find out how to multithread your code.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
 
H

hstagni

OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty to
me :p )
I am trying to convert my Pascal programs to C. But I made a Tetris
in Pascal, and the main loop of the program has a function that keeps
redrawing the screen with a delay(To make an animation) and this same
main loop reads a key from the keyboard that moves the objects on the
screen. On C, if i use getchar(), it would stop the animation and wait
for a key to be pressed: the game would suck :p
This FAQ you sent me does not applie(?) to my question(sorry if im
wrong). Of course I will have to use something like ncurses getchar().
However, this function has the same 'problem' i mentioned before: it
WAITS for a key, stopping my tetris animation :(

So, how can i do it?
In Pascal a simple "ch=readkey;" would solve my problem :(
 
K

Keith Thompson

hstagni said:
OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty to
me :p )

"while (1)" and "for (;;)" are the most common idiomatic ways to write
a loop in C. "while (1==1)" will just cause your readers to scratch
their heads.

[...]
This FAQ you sent me does not applie(?) to my question(sorry if im
wrong). Of course I will have to use something like ncurses getchar().
However, this function has the same 'problem' i mentioned before: it
WAITS for a key, stopping my tetris animation :(

Mark pointed you to question 19.1. Question 19.2 is actually more
applicable to what you're trying to do. But the conclusion is the
same: there's no way to do what you're trying to do in standard C, but
there's likely to be a system-specific way to do it (which you'll have
to ask about elsewhere).

And please learn to quote properly. The Google Groups interface does
this for you. You may find the following links useful:

http://cfaj.freeshell.org/google/
http://www.caliburn.nl/topposting.html
http://www.cpax.org.uk/prg/writings/topposting.php
 
J

J. J. Farrell

"while (1)" and "for (;;)" are the most common idiomatic ways to write
a loop in C. "while (1==1)" will just cause your readers to scratch
their heads.

Hardly. To someone who knows C its meaning is immediately clear. Since
it's an unusual form it might take a bit longer to parse, but even if
it takes as much as an extra hundredth of a second it's not that big a
deal. To people who haven't yet got a firm grasp of C's concept of
truth, it's meaning is probably far more obvious than the idiomatic
form.
 
A

Anthony Irwin

hstagni said:
OK,,,THANK YOU ALL
(I was trying to write while(1==1), cause for(;;) is kind of dirty to
me :p )

I am trying to convert my Pascal programs to C. But I made a Tetris
in Pascal, and the main loop of the program has a function that keeps
redrawing the screen with a delay(To make an animation) and this same
main loop reads a key from the keyboard that moves the objects on the
screen. On C, if i use getchar(), it would stop the animation and wait
for a key to be pressed: the game would suck :p

This FAQ you sent me does not applie(?) to my question(sorry if im
wrong). Of course I will have to use something like ncurses getchar().
However, this function has the same 'problem' i mentioned before: it
WAITS for a key, stopping my tetris animation :(

So, how can i do it?
In Pascal a simple "ch=readkey;" would solve my problem :(

<OT>
Have you looked at the NCurses howto it explains that by default it
will buffer the characters but by using raw() or cbreak() it will not
buffer the characters and send the key press directly to the program.

http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/init.html

There is even a code example of how to use it.
</OT>

Kind Regards,
Anthony Irwin
 
C

CBFalconer

hstagni said:
.... snip ...

So, how can i do it?
In Pascal a simple "ch=readkey;" would solve my problem :(

No it didn't. It may have on your particular Pascal
implementation, using some sort of extension. Same applies to C.
 
K

Keith Thompson

J. J. Farrell said:
Hardly. To someone who knows C its meaning is immediately clear. Since
it's an unusual form it might take a bit longer to parse, but even if
it takes as much as an extra hundredth of a second it's not that big a
deal. To people who haven't yet got a firm grasp of C's concept of
truth, it's meaning is probably far more obvious than the idiomatic
form.

I should have been clearer. Someone who knows C won't scratch his
head wondering "What does that mean?". He'll more likely scratch his
head wondering "Why didn't the author just write while (1)?".

Attempting to write "while (1==1)" also creates a vulnerability to the
error of writing "while (1=1)", which is exactly what the OP initially
did.
 
A

Anthony Irwin

What's wrong with for(;;) or while(1) ?

Is there any advantages over using a for or a while or are they
essentially the same? I know they perform the same task but is there
any technical benefits of one over the other e.g. one faster then other.

I normally use while(1) and never really considered using for(;;)


Kind Regards,
Anthony Irwin
 
J

J. J. Farrell

I should have been clearer. Someone who knows C won't scratch his
head wondering "What does that mean?". He'll more likely scratch his
head wondering "Why didn't the author just write while (1)?".

If it used integer constants as in this case, and especially if it
appeared all over the code, I'd just read it as useful documentation
meaning one of two things: "the author didn't really understand
'truth' in C and might be a newbie - so watch out" or "the author is
someone who likes doing things in his own idiosyncratic ways - so
watch out".

If he were comparing a variable to itself, or if this odd construct
only occurred once among lots of "normal" cases, I would scratch my
head worrying about its being a typo.
Attempting to write "while (1==1)" also creates a vulnerability to the
error of writing "while (1=1)", which is exactly what the OP initially
did.

True, though the compiler would slap his wrist hard for that so others
shouldn't end up having to read it.

Just to be clear - I'm not advocating using this style, but I think it
accidentally gives useful clues to subsequent readers rather than
puzzling them.
 
R

Richard Heathfield

Keith Thompson said:
"while (1)" and "for (;;)" are the most common idiomatic ways to write
a loop in C.

I disagree. I for one consider both these forms to be aberrations rather
than idioms. The most common idiomatic ways to write a loop in C are
surely:

for(i = start; i < stop; i += inc)

and

while(conditional_expression)


"while (1==1)" will just cause your readers to scratch
their heads.

No more so than the other two.
 
S

santosh

Anthony said:
<OT>
Have you looked at the NCurses howto it explains that by default it
will buffer the characters but by using raw() or cbreak() it will not
buffer the characters and send the key press directly to the program.

http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/init.html

There is even a code example of how to use it.
</OT>

But it'd still block for input, something the OP doesn't want. He
wants an asynchronous notification, on a key press.

He might have to look into signals, or as Mark McIntyre notes,
multithread his program.
 
J

jaysome

Keith Thompson said:


I disagree. I for one consider both these forms to be aberrations rather
than idioms. The most common idiomatic ways to write a loop in C are
surely:

for(i = start; i < stop; i += inc)

and

while(conditional_expression)




No more so than the other two.

The more conventional form of infinite loop prefix is
for ( ; ; )
 
R

Richard Heathfield

jaysome said:

The more conventional form of infinite loop prefix is
for ( ; ; )

I consider "infinite loops" to be an aberration, not an idiom.

Your turn.
 
C

Chris Dollin

Richard said:
jaysome said:



I consider "infinite loops" to be an aberration, not an idiom.

I've never seen an infinite loop, only specifications for them.

The preamble `while(1)` or `for(;;)` means, to me, "here is a
loop which C's collection of control structures doesn't give
me out of the box. Look out for some other idiom."

And the most common one of those [1] is the venerable n-and-a-half
loop:

while(1)
{
preamble();
if (doneCondition()) break;
postamble();
}

They happen often enough that I wish there were a more constrained
syntax that said that.

Now, this loop is (we hope) not infinite; does the `while(1)` trip
your abberation detectors, and what would your approach be to the
problem? [We may assume that there's no trivial function to extract
that can do the preamble-doneCondition business, on the grounds that
this is /me/, and if I though it could be done I'd already have done
it.]

[1] In my humble\\\\\\ experience.
 
R

Richard Heathfield

Chris Dollin said:

And the most common one of those [1] is the venerable n-and-a-half
loop:

while(1)
{
preamble();
if (doneCondition()) break;
postamble();
}

They happen often enough that I wish there were a more constrained
syntax that said that.

Yes, so do I. Nevertheless...
Now, this loop is (we hope) not infinite; does the `while(1)` trip
your abberation detectors, and what would your approach be to the
problem?

It does, because (in my very simplistic and naive view) while(1) is
making a promise that the break breaks, and I don't like breaking
promises if I can avoid it, so I would simply do this:

int done = 0;
while(!done)
{
preamble();
done = doneCondition();
if(!done)
{
postamble();
}
}

Yes, it's slightly more code. I don't find this to be a big deal,
although some people obviously do. Yes, it uses an extra object. I
don't find this to be a big deal, either, although some people
obviously do. But I /do/ find it to be clearer, although some people
obviously don't.
 
N

Nick Keighley

Anthony said:
(e-mail address removed) wrote:

Is there any advantages over using a for or a while or are they
essentially the same? I know they perform the same task but is there
any technical benefits of one over the other e.g. one faster then other.

I normally use while(1) and never really considered using for(;;)

they are funtionally identical (on any reasonable compiler).
for(;;) is a particular C idiom. Perhaps a bit "clever".
Apparently for(;;) is less likely to generate a warning.
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top