post and pre increment in for loop. string length without library function in C

303 views Asked by At

I am trying to find Length of a string w/o using library function.

char card[16];                  //card number in char array.
unsigned int cardno[16]={0};    //card number in int array for calculations.

int i,length=0,len;
printf("Credit Card Number[without any spaces]: "); 
gets(card);

for(i=0;card[i]!='\0';i++);
len=i;
length=strlen(card);

printf("%d %d",len,length);

But if i enter a 16 digit card number the output is 16 17 but otherwise[card number less than 16 digit] both output is same. Is this effect of pre and post increment or some other thing. Please explain.

2

There are 2 answers

2
DrKoch On BEST ANSWER

First, you need a longer char array for a 16 digit number:

char card[17];  // 16 digits + `\0`  

Then try this:

for(len=0; card[len] != '\0'; len++);

Do not rely on the value of i outside the loop.

1
Eric Tsui On

The quick answer is to use fgets() to replace the gets()

char *fgets(char *str, int n, FILE *stream)

n -- This is the maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used.

It is unsafe to use the function gets() which could cause stack overflow :) e.g. if you'd like to enter 16 digit card number into the card[16], there is no place to put '\0'.