0

I'm trying to write a programme with C that asks for a number to be input and then determines whether or not it is a prime number. If the input is a non-numeric character or string, it outputs the message INVALID INPUT. I have managed to create code that can determine if a number is prime and also if it is non-numeric but when I try and combine them, it doesn't work. E.g if I input a non-numeric value it will output the correct message but when I input a numeric value, nothing happens and I'm not sure why. Can anybody help?

#include <stdio.h>
#include <string.h>
#define FALSE 0
#define TRUE 1

int numeric( char *string )
{
    int i, valid;
    valid = TRUE;

    if (string[i] < '0' || string[i] >'9')
        valid = FALSE;
    return valid;
}

void main()
{
    char number[5];
    printf("Please enter a decimal number>");
    gets( number );

    if (numeric(number) == TRUE)
    {
        int n, i, a = 0;
        scanf_s("%d", &n);

        for (i = 2; i <= n / 2; ++i)
        {
            if (n%i == 0)
            {
                a = 1;
                break;
            }
        }

        if (n == 1)
        {
            printf("1 isn't a prime number.");
        }
        else
        {
            if (a == 0)
                printf("number entered is a prime number");
            else
                printf("number entered is not a prime number");
        }
    }
    else 
        printf("INVALID INPUT \n"); 
} 
Mike
  • 4,041
  • 6
  • 20
  • 37
Sid
  • 13
  • 3
  • Welcome to StackOverflow! Be sure to take the [tour](https://stackoverflow.com/tour) and visit the [help center](https://stackoverflow.com/help). Your code has a problem which may or may not be related to the behaviour you describe, but it needs to be solved, otherwise you are invoking dreaded undefined behaviour. You're using uninitialized `i` as an index into your string in `numeric`. It's up to the compiler to determine what `i` will be, which is a horrible idea in general. If you're lucky, it's gonna be 0. If not, who knows? – Michail Nov 25 '18 at 14:37
  • 1
    See [Why the `gets()` function is so dangerous it should never be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Jonathan Leffler Nov 25 '18 at 16:42

1 Answers1

2

In addition to the bug mentioned in @Michail's comment (failing to initialise i to zero in numeric:

Your problem is that in the truthy branch of if (numeric(number)), you call scanf_s, which will try to read new input from STDIN. You've already read the number from STDIN in your call to gets. The behaviour you observe ("nothing happens") is to be expected: your program is waiting for you to enter more input.

You leave yourself open to buffer overflow but that's a separate issue.

linguamachina
  • 5,785
  • 1
  • 22
  • 22