I've essentially solved my issue by slapping together a work around, but I'm just wanting to understand why this behavior happens so first my code:
#include <stdio.h>
#pragma warning(disable : 4996) // Just so MVS stops having a meltdown over scanf.
/* Simple question and answer of math equasion. */
int main()
{
printf("What is 5 + 5?
Answer: ");
int userInput;
if (scanf("%i", &userInput) && userInput != (5 + 5)) // Give 'userInput' a variable from scanf and compare to hard coded answer.
{
printf("
Incorrect!
");
return 0;
}
printf("
Correct!
"); // Else without the 'else'.
return 1;
}
It's simple enough, hard coded math question, and requesting an answer from the user. Intended response would be correct for the answer solved matching userInput
and anything that doesn't match is considered incorrect. When I pass it a bunch of letters or just simply "asdf" it treats it as correct and spits out a negative number: -858993460.
My work around is adding || userInput < 0
to my if statement like this:
if (scanf("%i", &userInput) && userInput != (5 + 5) || userInput < 0)
So essentially the issue has been treated with some flextape slapped on it but what I can't seem to answer is the question: "Why does it spit out that negative number no matter what letters or non-numeric characters I feed it?"
My apologies if this has already been answered. I tried searching with whatever keywords I could think of to no avail.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…