So basically it involves sodding scanf().

int NumericalAnswer;
int score = 0;
main()
{
    printf("Question 1: What's 4 x 3?\n");
    scanf("%d\n", &NumericalAnswer);
    if (NumericalAnswer == 12){
        printf("You got it right!");
	score += 1;
    }
}

Output

Question 1: What's 4 x 3?
12
9
You got it right!

As you may have worked out, it's making me type two answers before it'll progress. I've added a printf() at the end to check the value of NumericalAnswer, and it's of the first answer I enter. So my program will still produce the correct output eventually, I just don't want to have to enter the number twice.

Any help would be greatly appreciated.

Ed

Edited 6 Years Ago by NichtSoGut: n/a

See if you can find what I changed...

#include <stdio.h>

int NumericalAnswer;
int score = 0;

int main()
{
	    printf("Question 1: What's 4 x 3?\n");
	    scanf("%d", &NumericalAnswer);
    
	if (NumericalAnswer == 12)
	{
		printf("You got it right!");
		score += 1;
	}
	return 0;
}
Comments
Couldn't really have been more helpful!!

Oh... my... god.... that simple???
So you've removed the \n from the scanf line.
Sorry to be a pain, but any chance you could explain why that made such a difference?

So I ran it, and it doesn't enjoy the first set of data input. Is that because scanf is looking for a '-' but I've only entered numbers? How come it doesn't just keeping going 'til it finds the number?
And in relation to the code I posted, why couldn't I have the '\n'? I had to press RETURN to enter the data, so surely the scanf would have seen the '\n' and successfully continued. I guess not :P

This is an interesting problem. I understand what you're saying, Nicht, but I personally don't know the underlying cause for this phenomenon. I would, though, just encourage you make it a practice to end the practice of including \n in your scanfs; if you do that, you should be all right.

Edited 6 Years Ago by Jmknight: n/a

>And in relation to the code I posted, why couldn't I have the '\n'?
If there's whitespace in the format string, scanf will extract whitespace characters (any whitespace character, so '\n' is no different from ' ' or '\t' in both the stream and the format string) until the next non-whitespace character. You're essentially requiring input to end with non-whitespace, which is the opposite of what normally happens in line buffered I/O.

This article has been dead for over six months. Start a new discussion instead.