I am learning C and I\'m using \"getchar()\" to stop the command windows so I can see the exercises am doing but it just doesn\'t work. heres a sample:
#incl
you are getting a carriage return, the way i would get around it, define a char and just have it scan the carriage return,
char ch;
(before your getch() enter the following)
scanf("%c",&ch);
getchar();
should work this way, not the most efficient way to do this but works for me.
As mentioned already scanf leaves \n behind after reading user input.
Soultion: add getchar() straight after scanf.
That compensates scanf deficiency.
i.e.
int value;
printf("1. option 1.\n2. option 2.\n3. option 3.\n4. Exit\n\nMake an option: ");
scanf("%d", &value);
getchar();
switch (value)
The getchar() is reading the \n from the keyboard in scanf - see here for more info
I think you input a enter after inputting "1". It will be accepted by the getchar()
.So you can solve the problem simply by add an additional getchar()
after the original one(just before the return 0;
).
** I tested this and it worked.
in order for your program to work, you should "flush" your input stream before calling getchar() with a call to fflush(stdin). What this does is, when you type in you keyboard a number and then the return key, the input buffer gets both characters, for example '1' and '\n', and your call to scanf gets only '1' so the '\n' remains in the input buffer. When you call getchar, you are "gettin" that remaining '\n'. Flushing the input discards all the buffer.
First of all, do not use fflush() to clear an input stream; the behavior is undefined:
7.19.5.2.2 If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
The problem is that the trailing newline is not being consumed by the "%d" conversion specifier, so it's being picked up immediately by the getchar()
. There's no one best way to deal with this, but generally the approach is to read the whole line as text (using either fgets()
or scanf()
with a sized "%s" conversion specifier), which will consume the newline, then convert to the target data type using sscanf()
or strtol()
or strtod()
.