scanf usage

Jul 8, 2009 at 11:29pm
I'm using scanf to scan for simple user input (see below for an example of what I'm doing...), and if I try to use it multiple times to scan for a character, it ignores any try after the first. I have a feeling this has to do with the stdin not being cleared after the input, and it just reads the first input over again, but I have no idea how to fix this. I've read through the explanations of scanf on this and other websites and am still confused.

I want to first figure this out before I move on to trying cin. I think knowing why this isn't working would be very helpful to my understanding of C/C++ as a whole...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <stdio.h>

int main() {

char Ans[2];

printf("T/F: Austin is the capital of Texas.\n");

scanf("%c", &Ans[0]);

if(Ans[0] == 'T') 
	{

printf("Correct!");

	}

else 
	{
	
printf("Incorrect");

	}
	
printf("\nT/F: Texas is the Sunshine State.\n");

scanf("%c", &Ans[1]);

if(Ans[1] == 'F')

	{

printf("Correct!");

	}

else 
	{
	
printf("Incorrect");

	}

return 0;

}
Jul 8, 2009 at 11:41pm
The solution to your Problem is actually quite simple.
when u enter a key (or more than one) and press enter you read 2 (or more than 2) characters. Your characters + 1 newline.
Use for example " %c" (as many whitspaces as u want + character) instead of "%c" and u shouldn't have any problems any more.
Jul 8, 2009 at 11:46pm
Well, that certainly fixed the problem, but I'm still not certain I understand why. Is it that when I use "%c" it only wants to read 1 character, but by default when I enter "T" and press enter, there are two characters, and the next scanf is thrown off because of that?
Jul 8, 2009 at 11:55pm
Yes, the next scanf reads 13 as an decimal value the same as \n (newline).
So your input looks like this: "T\n"
1
2
scanf("%c", &Ans[0]); // reads T
scanf("%c", &Ans[1]); // reads \n (ENTER) 

If you added a third scanf your program would wait for a new input since it finds only 2 characters but then it would need 3.
1
2
3
scanf("%c", &Ans[0]); // reads T
scanf("%c", &Ans[1]); // reads \n (ENTER)
scanf("%c", &Ans[2]); // wait for a new input 
Jul 9, 2009 at 12:04am
Thanks, and one last thing:

If someone accidently entered more characters than I had prepped scanf for, it could cause problems the rest of the way, right?
Jul 9, 2009 at 12:19am
Exactly. Eg
1
2
3
4
5
6
7
scanf("%c", &Ans[0]); // input ABCDE reads A
scanf("%c", &Ans[1]); // reads B
scanf("%c", &Ans[2]); // reads C
scanf("%c", &Ans[3]); // reads D
scanf("%c", &Ans[4]); // reads E
scanf("%c", &Ans[5]); // reads \n
scanf("%c", &Ans[6]); // wait for new input 

You may want to have a look at getch() (POSIX) or _getch() of the conio.h header file.
Or maybe later _kbhit() for a little more complex usage of console input.
Topic archived. No new replies allowed.