Home > Back-end >  Store an incremented int number that is on a char variable
Store an incremented int number that is on a char variable

Time:04-29

I've been trying store the 1 to temp so that it increments the next time the function is ran again. The prints are just for debugging purposes.

void CreatAccountNumbers(char *startString)
{
    ACCOUNTNUM accountInfo;
    //this function is for the system generation of bank client account numbers
    int temp; //first int
    temp  ;
    char tempChar=temp; //int to char
    tempChar ='0'; 
    char finalString[30]=" ";
    strcpy(finalString,startString);
    printf("\nstartstring:%s",startString);
    printf("\ntempChar:%c",tempChar);
    printf("\nfinal string:%s",finalString);
    finalString[5] =tempChar;
    temp =tempChar;
    printf("\nfinal string with tempchar:%s",finalString);

    strcpy(accountInfo.sAccountNum,finalString);
    printf("\nvalue on structure:%s",accountInfo.sAccountNum);
}

CodePudding user response:

The variable temp was never initialized properly. So, it will produce undefined behavior.

You can initialize it like this:

  int temp = 0;

Now, finalString is not properly initialized, you should write it like this:

 char finalString[30]= {}; // all elements will be 0

Also, ASCII value 1 will not be printed on stdout.

CodePudding user response:

I think what you're looking for is something like this.

  • Use static qualifier to store the sequence number.
  • sequence will retain its value between calls to generate next account number.
  • NOTE : This value will reset once the program restarts. You may want to load the last sequence number from an external source during startup.
void ai_get_newACnum (const char* ac_prefix, char* new_ac, const size_t naclen) {
    static int sequence = 1;
    snprintf (new_ac, naclen, "%s_	d", ac_prefix, sequence  );
}

You can call for you structure like : sizeof if accountInfo.sAccountNum is an char-array, otherwise the actual dynamic-memory size.

ai_get_newACnum (startString, accountInfo.sAccountNum, sizeof(accountInfo.sAccountNum));

To test :

#define MAX_ACNUM_STRLEN 64

int main (void) {
    char nxtACNumber [MAX_ACNUM_STRLEN];
    for (int ai = 0; ai < 12;   ai) {
        ai_get_newACnum ("myAcSeq", nxtACNumber, sizeof (nxtACNumber));
        printf ("New Account Number : %s\n", nxtACNumber);
    }
    return 0;
}

Which generates :

New Account Number : myAcSeq_000000001
New Account Number : myAcSeq_000000002
New Account Number : myAcSeq_000000003
New Account Number : myAcSeq_000000004
New Account Number : myAcSeq_000000005
New Account Number : myAcSeq_000000006
New Account Number : myAcSeq_000000007
New Account Number : myAcSeq_000000008
New Account Number : myAcSeq_000000009
New Account Number : myAcSeq_000000010
New Account Number : myAcSeq_000000011
New Account Number : myAcSeq_000000012
  •  Tags:  
  • c
  • Related