简体   繁体   中英

C language determine length of array depending on amount of digits entered by the user

I have the below code in which a user enters their card number, with this each digit is stored as an element in the variable array digits[] .

What I am trying to achieve is to have the for loop stop after it has stored all digits, however, I am struggling to set the loop as per the length of the entered card number.

I have tried the below code using sizeof(cardNo) stored in the variable length and setting length as the loop condition.

Let's say the user enters 1234 the result I am receiving with the below code being run is 43210000, when what I am looking for is just 4321.

if I set int digits to digits[4] and the loop condition to < 4 it will give me 4321 but obviously this restricts me to user only entering 4 digits when in fact I want this to be flexible ie if they enter 6 digits it will give me 123456 if they enter 8 digits it will give me 12345678 etc.

Any ideas or suggestions, please?

long cardNo = get_long("Enter Card Number: ");
int length = sizeof(cardNo);
int count = 0;
int digits[length];

for (int i = 0; i < length; i++) {
  digits[i] = cardNo % 10;
  cardNo /= 10;
  printf("%i\n", digits[i]);
} 
printf("\n");

The length of a number is based on its logarithm base 10:

#include <math.h> //log10
....
    int len = log10(cardNo) + 1;
...

Don't forget to link with the math library ( gcc ... -lm )

Idiom: measure-allocate-generate.

size_t n =0;
for (; i < cardno; ) {
  cardNo /= 10;
  n++;
} 
if(!n)n++;//0
int*digits=malloc(n*sizeof(int));

The code may be simpler, considering a maximum amount of numbers (being developer's choice to store the fixed-size container on the stack, as static, etc):

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

#define STRINGIFY(x) STRINGIFY2(x)
#define STRINGIFY2(x) #x

#define MAX_NUMBERS 16

int main() {
    char cardNum[MAX_NUMBERS + 1];
    size_t sizeCard;

    printf("Enter card numbers\n");
    scanf("%" STRINGIFY(MAX_NUMBERS) "s", cardNum);
    sizeCard = strlen(cardNum);
    for (int i = 0; i < sizeCard; i++) {
        printf("%c\n", cardNum[i]);
    }
    printf("\n");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM