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

Recommended Answers

All 6 Replies

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;
}
commented: Couldn't really have been more helpful!! +0

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?

Try running this code

#include <stdio.h>

int one, two;

int main()
{
	printf("Enter two numbers->\n");
	scanf("%d - %d", &one, &two);
    
	fprintf(stdout, "one->%d, two->%d\n", one, two);
	
	return 0;
}

First enter your numbers like this

34 56

and then try entering your numbers like

34 - 56

Try this link

http://www.java-samples.com/showtutorial.php?tutorialid=564

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.

>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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.