2

I am new to Xcode development tool. To debug a problem, I have tried a very simple code:

int main()
{char N;
 char M;
 scanf("%c",&N);
 scanf("%c",&M);
 printf("%c",N);
 printf("%c",M);
}

But the problem is that the compiler doesn't seem to read the second scanf. So I can enter one character in the console, and then the program stops. Amazingly, when I write the same code with "int" in place of "char", it works just fine. Does anybody have an idea what's wrong?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
epsilones
  • 11,279
  • 21
  • 61
  • 85
  • Since you're a rank beginner, you should not presume that you know what the problem is ... and especially you should not presume that the problem is with the tool (even if you aren't a rank beginner). Thus, the title of your "question" is very bad. – Jim Balter May 14 '12 at 04:02
  • What do you see if you type `aa` and then enter? – Jonathan Leffler May 14 '12 at 06:34

1 Answers1

6

You're pressing Enter after typing a character into the first scanf, right? That Enter is what gets read by the second scanf. And printed by the second printf.

You haven't shown the output of this program, but if you change the printf formatting to %d\n from %c, then it's probably something like the following if you type "a" and press Enter:

97
10

That 10 is the character code for Enter (newline or line feed).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • And one way to fix the problem is to use the `%*c` format spec to 'eat' the newline by reading and discarding it: `scanf("%c%*c",&N); scanf("%c%*c",&M);` – Michael Burr May 14 '12 at 05:01
  • @JonathanLeffler: Yeah I thought about going into that level of detail (not in front of my Mac so I couldn't try it), so I settled on "...something like...". – Greg Hewgill May 14 '12 at 06:28
  • Wright thanks a lot for your instructive response ! Best, Newben – epsilones May 14 '12 at 12:35