0

I'm learning C and to get something done I need to ask the user to input 2 characters, like in this example: "b [enter] t". and store them in two different variables, but my code is not working that way.

Why doesn't this work? Is there a simple way to fix it?

void main(void){
int a,b;
printf("Input a char");
a=getchar();
printf("Input second char");
b=getchar();
printf("Characters entered: %c and %c.", a, b);
return 0
}
YoTengoUnLCD
  • 600
  • 7
  • 15

2 Answers2

0

The problem is that a will be set to 'b' but b will be set to '\n' (from Enter). If you want sane user input, always read a whole line first (e.g. with fgets), then process it (e.g. take the first character or convert it to a number, etc).

melpomene
  • 84,125
  • 8
  • 85
  • 148
-1

The \n stays in the buffer, your second getchar() reads it, so a is equal to the first char but b is equal to \n

To avoid this you can use a getchar() in between or use scanf()

scanf("%c\n%c", &a, &b);

You can also read the whole line as pointed out by others and then dissect it by using sscanf()

Alex Díaz
  • 2,303
  • 15
  • 24
  • It is a mistake to use `scanf` for user input. – melpomene Aug 22 '15 at 20:26
  • @melpomene I didn't want to over-complicate the answer as the OP seems to be just getting a grasp of the basics, your point stands though. – Alex Díaz Aug 22 '15 at 20:29
  • @melpomene a mistake?? the OP is learning C and for something as simple as his question i don't see why the use scanf would be a mistake.. Why over-complicate the solution? – Ben cisneros Aug 22 '15 at 20:36
  • @Bencisneros `scanf` is not a tool for beginners. Why overcomplicate the solution by introducing something as unpredictable and fragile as `scanf`? – melpomene Aug 22 '15 at 20:38
  • @melpomene it is a tool for beginners, sure it will usually lead to bugs on real projects but for poking around and learning the language it works, and it's what most people are told to use at the beginning I think. – Alex Díaz Aug 22 '15 at 20:39
  • @AlejandroDíaz It is absolutely not a tool for beginners, and it does not work for learning the language, as evidenced by how many questions there are along the lines of "why does my program skip over user input?", etc. My main objections are: `scanf` is not line based, which is what most users expect from an interactive program; error detection is barely possible but error recovery is pretty much impossible; it has too many weird features and corner cases (e.g. why does your answer suggest `"%c\n%c"` and not `"%c %c"` or `"%c\t%c"`? they all mean the same thing). – melpomene Aug 22 '15 at 20:49
  • @melpomene When you're learning how to declare variables and such you don't care about error recovery just yet, sure it is better to use `fgets()` and `sscanf()` but this just adds complexity for a beginner. As for the last parenthesis, `sscanf()` still has this quirks I think – Alex Díaz Aug 22 '15 at 20:55