473,657 Members | 2,476 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

scanf reads getch

Hi,

Consider the program snippet below

main
{
....
printf("Enter Choice: ");
int choice = getche();

switch(choice)
{
case '1':
printf("Enter Num:");
int num;
scanf("%d", &num);
.....
break;

// some other cases like '2', '3' etc

case '5':
int x = getche();
...
}
}

My problem is when i type 1 or 2 for the "int choice = getche", I land
on the right case but the scanf reads and displays the previuously
entered character. But that does not happen for case '5'. I tried using
fflush(stdin) still it does not work.

Let me know what is wrong with my usage.

Thanks
Vivek Ragunathan

Nov 15 '05 #1
4 2764
In article <11************ **********@o13g 2000cwo.googleg roups.com>,
VivekR <Ke*****@gmail. com> wrote:
Consider the program snippet below main
You are missing the prototype for main.
{
...
printf("Ente r Choice: ");
You are not flushing the output buffer and you are not putting out \n
that would in -some- contexts allow the buffer to be flushed automatically.
Your prompt is not certain to appear before the read takes place.
[On most systems that I've encountered, the prompt will -not- appear
before the read takes place.]
int choice = getche();
You haven't given a definition for getche().
switch(choic e)
{
case '1':
printf("Ente r Num:");
See above about buffer flushing.
int num;
Compatability note: C89 does not permit variables to be declared after
active code; in C89, variables may only be declared at the beginning
of a block.
scanf("%d", &num);
....
break; // some other cases like '2', '3' etc case '5':
int x = getche();
..
}
}
My problem is when i type 1 or 2 for the "int choice = getche", I land
on the right case but the scanf reads and displays the previuously
entered character. But that does not happen for case '5'.
We would need to see getche() to make a proper assessment.

What we can say is that after you type the 1 or 2, then unless
getche() does some funky things, you would need to press newline
for the choice to be passed from the system buffers into your program.
Telling C to read a single character does NOT tell the system to
pass on the characters as soon as they are typed (and, before you
ask: No, there is NO portable way to tell the system to pass on
characters as soon as they are typed, and NO, setting stdin to
be unbuffered does NOT accomplish that.)

If you were doing a getchar() then that newline would be left
in the input buffer, and then the newline (and all leading whitespace)
would be skipped by scanf() with %d format, so scanf would read the
number as you expected.

As that is not happening, we can make guesses about what getche() is
doing, but we don't know. We could guess, for example, that
in your implementation, the "e" part of the getche() name stands
for "examine", and thus that after the character has been read,
it is ungetc()'d back into the input stream, there to be read again.
But that's speculation, and you would have to provide the source
for getche() for us to be sure.
I tried using
fflush(stdin ) still it does not work.


fflush() is not defined for input files.
--
Feep if you love VT-52's.
Nov 15 '05 #2

[snip]
int choice = getche();


You haven't given a definition for getche().

[snip]

If walter did more research he would find that getche() is the echo
version of getch() in the <conio.h> header file.

Anyway, it is not really standard C library, so maybe you should
refrain from using it, and use getc() instead. One extra Enter won't
kill the program.

Nov 15 '05 #3
In article <11************ **********@g49g 2000cwa.googleg roups.com>,
Steven <so************ ******@yahoo.co m> wrote:
>int choice = getche();
You haven't given a definition for getche().
If walter did more research he would find that getche() is the echo
version of getch() in the <conio.h> header file.
If Steven did more research, he would find that the first 6 google
hits on conio.h do not define getche() [though one defines _getche()].
Not until hit 7, a French index of Borland C functions, do we find
any kind of definition. conio.h has about 69000 google hits, but
only 4200 hits for conio.h getche . A number of those hits indicate
that one must include <windows.h>.

Anyway, it is not really standard C library, so maybe you should
refrain from using it, and use getc() instead. One extra Enter won't
kill the program.


"not really standard C library" ?? It isn't even provided by gcc.

You know the rule around here: if a referenced routine
isn't defined in the Standard then unless the code for it is given,
any and all behaviour may be imputed to the routine.

Some of the hits I find for getche() indicate that it flushes console
output before doing the read; most don't make any mention of that
behaviour. Clearly it is implementation specific, and absent
a definition of the routine, the interaction with buffered I/O is
undefined.
--
"[...] it's all part of one's right to be publicly stupid." -- Dave Smey
Nov 15 '05 #4


Steven wrote:
[snip]
int choice = getche();
You haven't given a definition for getche().


[snip]

If walter did more research he would find that getche() is the echo
version of getch() in the <conio.h> header file.


Nonsense. getch() returns a pointer to the piece
delivering check to the King, or NULL if the King is not
in check. If the King is in check, getche() returns a
pointer to the "extra" checking piece if a double check
exists, or returns NULL for a single check.

Piece *p;
p = getch(); /* first attacker */
if (p == NULL) {
printf ("The King is not checked.\n");
}
else {
printf ("The King is checked by the %s at %s",
p->name, p->location);
p = getche(); /* extra attacker */
if (p != NULL)
printf (" and by the %s at %s",
p->name, p->location);
printf (".\n");
}
Anyway, it is not really standard C library,
.... which is why Walter Roberson (you lost the attribution)
said no definition had been supplied.
so maybe you should
refrain from using it, and use getc() instead. One extra Enter won't
kill the program.


Agreed, heartily. But see Question 12.18 in the FAQ

http://www.eskimo.com/~scs/C-faq/top.html

--
Er*********@sun .com

Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
3083
by: Kris | last post by:
Hi! I have the following instruction: char wyp; scanf("%c",&wyp); this scanf is in a while loop, and I want it to get EXACTLY one character each time. Does anyone knows how to do it? BTW. How can I get information how many characters were entered and assigned to variable wyp?
12
9842
by: B Thomas | last post by:
Hi, I was reading O'Reilly's "Practical C programming" book and it warns against the use of scanf, suggesting to avoid using it completely . Instead it recomends to use using fgets and sscanf. However no explanation is offered other than that scanf handels end of lines very badly. I have exeperienced such problems when doing some numerical programming but never understood it. Things like some consequitive scanfs would not read in values...
7
7653
by: hugo27 | last post by:
obrhy8 June 18, 2004 Most compilers define EOF as -1. I'm just putting my toes in the water with a student's model named Miracle C. The ..h documentation of this compiler does state that when scanf cannot fill any fields it returns EOF. I have run some tests on scanf and, so far, I've not found an EOF return. For example: If the programer formats scanf for an int or
3
2753
by: Vinicius | last post by:
Hello, the following code does not work: " .... void main(void) { char option; printf("Choose an option: ");
185
17343
by: Martin Jørgensen | last post by:
Hi, Consider: ------------ char stringinput ..bla. bla. bla. do {
18
11840
by: Martin Jørgensen | last post by:
Hi, Today I got a really strange problem... I've made myself a data-file and I read in data from that file.... When I read something like this line: 03 04 05, 00 04 01, 05 03 07, 08 03 00, 09 06 03 ... etc. with something like scanf("%i %i %i, ", &var1, &var2, &var3);
8
2189
by: john | last post by:
I'm trying to use scanf() to get a string that is terminated by a $sign: Reading a file line that has: account number, name (terminated by $sign) and six numbers: 000001 John Doe$ 4 5 6 7 8 9 I'm trying to read it in like so: int ret, acct, c1, c2, c3, c4, c5, c6;
26
4519
by: tesh.uk | last post by:
Hi Gurus, I have written the following code with the help of Ivor Horton's Beginning C : // Structures, Arrays of Structures. #include "stdafx.h" #include "stdio.h" #define MY_ARRAY 15
5
610
by: Jack | last post by:
Hi, can someone tell me what is wrong with this code. cout << "Enter the size of the array:"; cin >size; myVar = new char; myVar = 'a'; printf ("%c\n",myVar); puts ("Enter value for the first cell: ");
0
8420
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8842
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8516
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8617
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.