0

I'm not well versed in C and I'm unsure how to get it to loop if the 9 digits are not entered

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

int main()
{

    char NIN[9];

    printf("Please enter your 9 digit NIN:\t");
    scanf(" %s", &NIN);

What I have will overflow if you enter more than 9 which isn't what I want

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
tyna 007
  • 11
  • 1
  • 2
    C strings have a NUL byte at the end. So if you want **an array of digits that isn't a string**, you'll need to read one character at a time with `getchar`. If you want **an array of digits that is a string**, you'll need a bigger array. – user3386109 Jan 09 '23 at 20:30
  • 1
    The `char NIN[9];` can't even hold a 9 digit *string*. Anyway, unless you have very strict memory constraints, always be generous with your buffer sizes. That makes it easier to read and discard inputs that are too long, instead of leaving the excess in the input buffer, to interfere with a subsequent input. As you would with the corrected `scanf("%8s", NIN);` No space or ampersand are needed here. – Weather Vane Jan 09 '23 at 20:30
  • Welcome to the world of off-by-one errors. – tadman Jan 09 '23 at 21:21
  • Apart from the array size issue already pointed out, you should read [How to prevent `scanf()` causing a buffer overflow in C?](https://stackoverflow.com/q/1621394/15168). And the general answer to the question "how can I stop users from entering the wrong value" is "You can't". However, you can detect that they entered the wrong stuff and get them to try again (or reject the request, or …). Read the entire line using `fgets()` or POSIX `getline()` (use a biggish buffer — 4096 bytes, or more if you prefer), and analyze what they entered. – Jonathan Leffler Jan 10 '23 at 00:28

0 Answers0