-
getch() acting up...
OK, I put together a little app to show how pointers work, to be uploaded to my website. However, getch() doesn't seem to be stopping the program unless I have two of them. It acts the same no matter where the first one is, but the 2nd one has to be just before return.
Using Dev-C++ on NT 4.
Code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void foo(int *y);
int main(int argc, char *argv[])
{
int x = 100;
int *y = 0;
y = &x;
printf("Enter your number: ");
scanf("%d",&x);
printf("The value of x is: %d \n",x);
printf("The address if x is: %d \n",&x);
printf("The value of y is: %d \n",y);
printf("The value at that address is: %d \n",*y);
getch();
foo(y);
printf("The new value of x is: %d \n",x);
printf("The address if x is: %d \n",&x);
printf("The value of y is: %d \n",y);
printf("The value at that address is: %d \n",*y);
getch();
return 0;
}
void foo(int *y)
{
*y += 125;
}
-
I think (but am not sure) that the scanf may be leaving the \n in the stream which the getch reads as a keypress. Try adding a fflush(STDIN) after the scanf.
-
Thnx, s_c, it worked (once I changed STDIN to stdin :))
-
fflush(stdin); is an undefined operation - so it works for you, but it doesn't work for me.
If you want to avoid all the mess which scanf leaves behind, then do this.
Code:
char buff[BUFSIZ];
fgets( buff, BUFSIZ, stdin );
sscanf( buff, "%d", &x );
So it's a bit longer, but at least you know where you are in the input stream.
And it's a lot easier to recover from errors, you might expect someone to type in "42", but if they type in "fourty-two", simple scanf calls are in a world of pain.
-
why is that undefined salem?
is stdin not a file?
-
mmmm autologging in not working prperly now!
-
On DOS yes fflush(stdin) may "work", your already
using getch so your not going anywhere but
dos and borland's compiler. Ofcourse "work"
is really up to whoever's implementing it as
it's undefined by the standard.
It doesn't work on linux, if you absoutly must get some out of the input stream you can do
Code:
int c;
while((c = getc(stdin)) != EOF)
;
Your best off just using fgets.
-
Before someone notices ...
Code:
int c;
while((c = getc(stdin)) != EOF && c != '\n')
;
-
if i remember correctly this should handle clean up after scanf in the same function call
scanf("%d %*c", &x);
the %*c will read in '\n' but skip the arguement so it won't cause any problems.
-
why does it keep loggin me out???
the above unregistered post is mine...