0

so i want to have application that validates input. if the input was an integer/digit it will ask for number again. but if it wasnt, it will print that this is not a number and asks for number again. but before asking for number again, i want to let the user press any key to continue.

thats my code :

#include <stdio.h>
#include <math.h>
#include <conio.h>

int main() {
    printf("\t\tWelcome To Prime Check App\n");
    while (1) {
        printf("\n\n\t[*] Enter Number: ");
        int num;
        int checknum = scanf_s("%d", &num);
        if (checknum == 0) {
            printf("\n\t[-] Not A Number!");
            _getch();
        }
    }
}

and thats the output:

                Welcome To Prime Check App


        [*] Enter Number: 1


        [*] Enter Number: 2


        [*] Enter Number: 3


        [*] Enter Number: hello

        [-] Not A Number!

        [*] Enter Number:
        [-] Not A Number!

        [*] Enter Number:
        [-] Not A Number!

        [*] Enter Number:
        [-] Not A Number!

as you can see, it asks for a character after it prints "Not A Number" but after pressing Every button , it will also skip the scanf_s()

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
iHapiW
  • 1
  • 2
  • 1
    OT, but `scanf_s()`?? Just use `scanf()`: [**Field Experience With Annex K — Bounds Checking Interfaces**](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm). "A widespread fallacy originated by Microsoft's deprecation of the standard functions in an effort to increase the adoption of the APIs is that every call to the standard functions is necessarily unsafe and should be replaced by one to the "safer" API." and " ... the implementation is incomplete and conforms neither to C11 nor to the original TR 24731-1. ... – Andrew Henle Oct 24 '21 at 15:04
  • 1
    (cont) ... As a result of the numerous deviations from the specification the Microsoft implementation cannot be considered conforming or portable." – Andrew Henle Oct 24 '21 at 15:04
  • Is it a requirement of the assignment to detect and skip past bad input, or just something you thought might be nice? – Steve Summit Oct 24 '21 at 15:05
  • 1
    Detecting and skipping past bad input using `scanf` is notoriously difficult. Three possible answers: (1) just don't bother; (2) flush the offending input somehow; (3) read full lines of text using `fgets`, then parse (perhaps using `sscanf`). For further info on these, see (1) [this answer](https://stackoverflow.com/questions/2979209/using-fflushstdin/58884121#58884121); (2) [this question](https://stackoverflow.com/questions/7898215); and (3) [this question](https://stackoverflow.com/questions/58403537). – Steve Summit Oct 24 '21 at 15:12
  • Fixed your title: `_getch` is not the same as `_getchar`. – Nate Eldredge Oct 24 '21 at 15:30
  • I think `_getch` bypasses the stdio buffers and so it can't really be used in conjunction with the `scanf` family. – Nate Eldredge Oct 24 '21 at 15:32

0 Answers0