0

In my homework assignments I've got a task to get an input using scanf() of an integer number and check if its a positive negative or zero.

I've coded this:

#include <stdio.h>

int main() 
{
    int num;
    printf("Enter a number: ");
    if (scanf("%d", &num) != 1) // Input validation
    {
        printf("Input error!\n");
        return 1;
    }
    if (num > 0)
    {
        printf("The number is positive!\n");
    }
    else if(num == 0)
    {
        printf("The number is zero!\n");
    }
    else
    {
        printf("The number is negative!\n");
    }
    system("pause");
    return 0;
}

The code is fine but when I've tested it with inputs of "0/" or "1ab6" and it only got the first number and ignored the /? or ab6?

I would like to read or get an explanation about how it works in the memory.

New contributor
CallMeEdwin is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
13
  • 1
    // Input validation (scanf is unsafe) wat? no. You should definitely explain why you come to write that comment! Commented Nov 17 at 15:04
  • 1
    another hint: when your compiler gives you warning for a simple program like this maybe don't disable them. They might tell you what's wrong. Commented Nov 17 at 15:05
  • 4
    Memory leak is a term for when you forget to clear heap memory that you explicitly allocated. This will only happen in C with things like the malloc family of functions. Commented Nov 17 at 15:21
  • 1
    @MarcusMüller The MSVC compiler is unsafe and considered harmful. Commented Nov 17 at 15:22
  • 1
    Microsoft C is not Standard C and litters the code with warnings when you do use Standard C functions. There are so many they obscure relevant warnings, but instead of disabling warnings place these three lines before the first #include directive: #define _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE. About scanf() you should spend at least an hour, possibly more, exploring how it works hands-on with the man pages in front of you. Commented Nov 17 at 17:09

1 Answer 1

9

The issue is not a memory leak.

scanf("%d", &num) does not scan input up to the entire line, but only up to the end of the numeric input.
Trailing text is left for the next scanf() call.

Sign up to request clarification or add additional context in comments.

2 Comments

Also, you can verify how many bytes scanf read using the format specifier %n. An example is shown here: geeksforgeeks.org/c/n-in-scanf-in-c-with-example
"%n" may be used. I find " %n" better. Unfortunately, The overly simplistic URL code fails to check the return value of scanf() nor initialized check before using it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.