0

I was assigned to make an user input a 5 digit number, validate it and print it back in a reversed order, I have the reverse part figured out yet I am struggling to figure out how to validate the variable in order to force the user to use 5 digits

#include <stdio.h>
int main() {
    int n, inv = 0, inverso;
    printf("Introduce un numero de 5 digitos: ");
    scanf("%d", &n);
    while (n != 0) {
        inverso = n % 10;
        inv = inv * 10 + inverso;
        n /= 10;
    }
    printf("El numero invertido es = %d", inv);
    return 0;
}
  • 5
    What should you do if there are more than 5 digits? Or non-digits in the input? – Vlad Feinstein Mar 08 '21 at 21:42
  • 1
    The input value is `>= 10000` and `<= 99999` but what if it ends with one or more zeros? The output by your method will ignore them unless you use `%05d`. When the input is `32100` you'll then get `00123` instead of `123`. – Weather Vane Mar 08 '21 at 21:43
  • 1
    Are leading zeroes allowed in the input? – Fred Larson Mar 08 '21 at 21:45
  • It would need to request the user to repeat the input until the 5 digit condition is fulfilled and yes, zeroes are allowed – Irving Lopez Mar 08 '21 at 21:46
  • Does this answer your question? [C Programming - Limit user to type certain amount of characters](https://stackoverflow.com/questions/35023416/c-programming-limit-user-to-type-certain-amount-of-characters) – the23Effect Mar 08 '21 at 22:03

6 Answers6

2

I would read into a character string, validate that the length is 5, and all characters are digits. Prompt to repeat if validation failed.

Then simply print that string in reverse order.

For example:

int n, inv = 0, inverso;
char buff[100];
int repeat = 1;
while (repeat) {
    printf("Introduce un numero de 5 digitos: ");
    scanf("%s", buff);
    repeat = 0; 
    if (strlen(buff) != 5) {
        printf("You must type 5 digits\n");
        repeat = 1;
        continue;
    }
    for (int i = 0; i < 5; ++i) {
        if (!isdigit(buff[i])) {
            printf("%c is not a digit\n");
            repeat = 1;
            continue;
        }
    }
}
printf("\nEl numero invertido es = ");
for (int i = 4; i >= 0; --i) {
    printf("%c", buff[i]);
}
Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27
2

You could reject the input if it is greater than 5 and signal it to the user, or you could truncate the input (after validating it) to prevent overflowing the maximum size. For instance :

if (strlen(string) > 5) string[5] = '\0';

Then continue normally (possibly signaling to the user that its input has been truncated) (the advantage being not to force the user to input again).

dspr
  • 2,383
  • 2
  • 15
  • 19
1

Since you're already processing the user input number digit-by-digit in a loop, it makes sense to just add a count variable initialized at 0 that increments each loop iteration:

int count = 0;
while (n != 0) {
        inverso = n % 10;
        inv = inv * 10 + inverso;
        n /= 10;
        count++;
    }

There are count digits in your user's input.

That said, in this case, unless your homework assignment or exercise prohibit processing the user input as a string instead of an integer, that really is the way to go because it's a lot simpler.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
1

Here is a simple test to check that n has 5 digits:

if (n >= 10000 && n <= 99999) {
    // n has 5 digits
} else {
    // try again
}

Here is a modified version:

#include <stdio.h>

int main() {
    int c, n, inv;

    for (;;) {
        printf("Introduce un numero de 5 digitos: ");
        if (scanf("%d", &n) == 1 && n >= 10000 && n <= 99999)
            break;
        while ((c = getchar()) != '\n') {
            if (c == EOF)  // unexpected end of file
                return 1;
        }
        printf("Invalid input, try again\n");
    }
    inv = 0; 
    while (n != 0) {
        inv = inv * 10 + n % 10;
        n /= 10;
    }
    printf("El numero invertido es = %d\n", inv);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
1

Use fgets() to read the input as a string. Later validate that the input is no longer that 5 digits and parse it with sscanf(). Even better you can avoid converting it and just print it in reverse.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LENGTH 500

int main()
{
    char buff[500] = {0};
    char *numbers = "0123456789";

    if (!fgets(buff,MAX_LENGTH,stdin))
    {
        fprintf(stderr,"input error...\n");
        exit(EXIT_FAILURE);
    }

    buff[strcspn(buff, "\n")] = 0; /* removing newline character from the buffer */

    if (strspn(buff,numbers) != strlen(buff)) /* making sure input is only numbers */
    {
        printf("only numbers allowed\n");
        exit(EXIT_FAILURE);
    }

    for (size_t i = 0, len = strlen(buff); i <= len; i++)
    {
        putchar(buff[len-i]);
    }


  return 0;
}

sscanf() alternative :

if (!fgets(buff,MAX_LENGTH,stdin))
{
    fprintf(stderr,"input error...\n");
    exit(EXIT_FAILURE);
}

if (sscanf(buff,"%ld",&number) != 1) /* always check the result of scanf() */
{
    fprintf(stderr,"input failure\n");
    exit(EXIT_FAILURE);
}

/* reverse the number */
alex01011
  • 1,670
  • 2
  • 5
  • 17
1

I would try a more unorthodox way since your input is already a String(char).

#include <stdio.h>
int len;
char buff[100];
int main()
{
     
     scanf("%s", buff);
     
     len = strlen(buff);
     
}

From there you have the length of the string stored in an int form in variable len.

You will continue by coding the if that handles what happens when len is greater than 5.

Hope i helped!

Spiros
  • 99
  • 10