shifting elements in an array of strings and fill with zeros

前端 未结 2 1874
梦毁少年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:55

    #include 
    #include 
    #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;
    }
    

提交回复
热议问题