Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

c - Scanf %i with letters gives negative number?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The scanf function returns the number of items matched, so in a boolean contents it evaluates to true if you entered a number and false if your didn't. It also means that no value is written to userInput, so its value (because it was not initialized) is still indeterminate.

This means your condition says that the answer is "Incorrect" if the user entered a number and it's not 10, so it's considered correct if you didn't enter a number. You instead want to print "Incorrect" if either a number is not entered or the entered number is not 10:

if (!scanf("%i", &userInput) || userInput != (5 + 5)) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...