the using of scanf

my code is like this :

char n;
for(;scanf("%c\n",n););

my problem is : when I key in the first char ,It can not stored in char 'n',the second will. but I want to get the first char which I key in. what's wrong ?

I complied the code in micsoft vistual stdio 2005.
You always get the last char you typed. Use an array to store all chars. Like:

1
2
3
4
5
char x[100];
for(int i = 0; i < 100; ++i)
{
  scanf("%c\n",x[i]);
}
That code does not behave like the original. You would want something more like this:

1
2
char x[1000];
for (int i=0; i<sizeof(x) && scanf("%c\n",x[i]); ++i);


Nevertheless, what you are doing doesn't look kosher. What exactly are you trying to accomplish?
Whoops:
1
2
3
4
5
6
char x[100];
for(int i = 0; i < sizeof(x) /*well ok*/; ++i)
{
  if(scanf("%c\n",x[i]) <= 0)
    break;
}
Dang, I forgot about that EOF!

1
2
3
char x[1000];
for (int i=0; i<sizeof(x) && scanf("%c\n",x[i])>0; ++i)
  ;
(Same as coder777's.)
I code like this : It also can resolve this problem.

char n;
scanf("%c\n",n);
fflush(stdin);


thanks coder777 and Duoas
thanks for the replies of everyone. good luck!
Oh, I get what you are trying to do...

fflush(stdin); is wrong, so don't do it. Instead just read to the end of the line.

http://www.gidnetwork.com/b-57.html
http://www.daniweb.com/software-development/cpp/threads/90228

Good luck!
thanks Duoas, fflush() is wrong ,I guess the reason is that your complier is gcc . but it is real a bad ideas to use fflush(). The links you give is very useful.
Last edited on
The reason is that it is countermanded by the standard, but anyway, you're welcome. :-)
Topic archived. No new replies allowed.