shifting elements in an array of strings and fill with zeros

前端 未结 2 1849
梦毁少年i
梦毁少年i 2021-01-25 08:58

I want to shift elements in my array to right and fill the shifted elements with zero (as string) . but it\'s a bit more difficult than i thought.

this program reads a t

相关标签:
2条回答
  • 2021-01-25 09:53

    Good start with your code.

    Since you're reading strings you can just use string manipulation. If you wanted to read them as ints you could determine the size with a logarithm function, but that would be overkill.

    You could save the numbers as ints, but then you'd have to defer the padding until you printed them later or saved them to a file.

    The easiest way to left pad the numbers with zeroes would be to use sprintf() with the correct format specifier to right justify the number. Then you can iterate through each character of the result and replace space e.g. ' ' with '0'. That will create left-side 0-padded entries. E.g. sprintf right justifies your number in a buffer that has room to hold the max sized number you can read, leaving spaces on the left.

    Then in a loop indexing one character at a time in the entry, and based on MAX_NUMBER_LEN shown below, you skip extra spaces on the left you don't want zeroes in (e.g. MAX_NUMBER_LEN - maxPaddingLenYouCalculateAtRuntime), and start replacing with zeroes.

    Then it's just a matter of creating a buffer whose address you'll pass to sprintf() that has enough space allocated to hold the result. That will have to be as big or bigger than your max length. I would call it maxStrLen rather than e, because naming variables for what they're used for makes for an easier to understand and maintain program.

    You have a few choices as to how to allocate that buffer of the right size, including using malloc(). But it is probably easier to determine the maximum size that an integer could be. There's even a C constant that tells you what a 32-bit or 64 bit Integer max. value is, and create an char array of fixed length entries based on that size in advance.

    For example:

    #define MAX_ENTRIES = 10
    #define MAX_NUMBER_LEN = 15
    char numbers[MAX_ENTRIES][MAX_NUMBER_LEN]
    

    That would give you the storage to store your sprintf() results in. Example:

    sprintf(numbers[entryNumber], "*right-justifying format specifier you look up*", numberReadFromFile)
    

    Wherein entryNumber is which slot in the array you want to store the result.

    The MAX_NUMBER_LEN part you don't need to include when getting the address for sprintf (notice I just passed in numbers[entryNumber], but not the 2nd set of brackets, intentionally). Because by omitting the second set of brackets, you're saying you want the address of the specific [MAX_NUMBER_LEN] chunk corresponding to the entryNumber, inside the numbers array. Note, there is no & on numberReadFromFile either, because you are reading them into a char array as strings, and because you're passing the address of the first char of an array you can just pass the array name. Alternatively you could pass in &numberReadFromFile[0] to get the address of the first element to pass to sprintf().

    And when using arrays that way, you don't need the & character to get the variable address to pass to sprintf(), as you would if you were not passing in an array element, because arrays really are simply another notation for pointers in C, and understanding how that works in general is the key to being effective with C in general and worth the initial struggle to comprehend.

    Here's an example of how to do the actual zero padding, based on what you got into your array from sprintf. I won't code up a full example because learning C is about the struggle to actually do it yourself. There's no shortcut to real comprehension. I'm giving you the hardest to discover aspects, by you working it through and making a solution of it, you'll gain quite a bit of mastery. This code is off the top of my head, not compiled and tested. It would either work or be close to working.

    /* numberToPad is a buffer containing a right-justified number, e.g. a number
     * shifted-right by sprintf(), in a buffer sized 15 characters,
     * space-padded on the left by sprintf's right-justifying format specifier.       
     * We want to convert the number to a 10-digit zero-padded number
     * inside a 15 character field. The result should be 4 spaces, followed
     * by some zeroes, followed by non-zero digits, followed by null-terminator.
     * example: "ƀƀƀƀ0000012345\0" where ƀ is a space character.
     */
    
    #define MAX_NUMBER_LEN 15  /* note: 15 includes null-terminator of string */
    int maxNumberLenActuallyRead = 10;
    int startZeroPaddingPos = MAX_NUMBER_LEN - maxNumberLenActuallyRead
    char numberToPad[MAX_NUMBER_LEN]; 
    int i;
    for (i = 0; i < MAX_NUMBER_LEN; i++) {
        if (i < startZeroPaddingPos) 
            continue;
        if (numberToPad[i] == ' ')
            numberToPad[i] = '0';         
    }
    
    0 讨论(0)
  • 2021-01-25 09:55
    #include <stdio.h>
    #include <string.h>
    #define SIZE_MAX 20
    
    int main()
    {
    
        FILE *fPTR;
    
        char num_first[SIZE_MAX]; // string input
        char num_second[SIZE_MAX];
        char num_zeros[SIZE_MAX];//array for leading zeros
        int i = 0;
        char numbers[SIZE_MAX];
    
        if ((fPTR = fopen("input.txt", "r")) == NULL) // our file contains two line of integers. one at each
        {
            puts("File could not be opened.");
        }
        else
        {
            if (fgets(num_first, SIZE_MAX, fPTR) != NULL) // reads first line and saves to num_first
                puts(num_first); // prints first number
            if (fgets(num_second, SIZE_MAX, fPTR) != NULL) // reads second line and saves to num_second
                puts(num_second); // prints second number
            fclose(fPTR);
        }
        for ( i = 0; i < SIZE_MAX; i++)
        {
            num_zeros[i] = '0';//fill array with '0's
        }
        // getting strings lengths
        int fLEN = strlen(num_first);
        if ( fLEN && num_first[fLEN - 1] == '\n')
        {
            num_first[fLEN - 1] = '\0';//remove trailing newline
            fLEN--;
        }
        int sLEN = strlen(num_second);
        if ( sLEN && num_second[sLEN - 1] == '\n')
        {
            num_second[sLEN - 1] = '\0';//remove trailing newline
            sLEN--;
        }
        int e = 0; // difference between two string lengths
        // here we get the difference and it's the place which i want to shif the arrays
        if (fLEN>sLEN) // first string is bigger than second
        {
            e = fLEN-sLEN;
            num_zeros[e] = '\0';//terminate array leaving e leading zeros
            strcat ( num_zeros, num_second);
            strcpy ( num_second, num_zeros);
        }
        else if (sLEN>fLEN) // second string is bigger than first
        {
            e = sLEN-fLEN;
            while ( fLEN >= 0)//start at end of array
            {
                num_first[fLEN + e] = num_first[fLEN];//copy each element e items from current location
                fLEN--;// decrement length
            }
            while ( e)// number of leading zeros
            {
                e--;
                num_first[e] = '0';// set first e elements to '0'
            }
        }
        else // there is no difference between two strings
        {
            //e = fLEN-sLEN;
        }
        puts(num_first);
        puts(num_second);
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题