How to print character array in reverse order of C program

自古美人都是妖i 提交于 2019-12-13 07:41:30

问题


#include <stdlib.h>
#include <stdio.h>
#define SIZE 25

int main (void)
{

        int d, b, c;

        printf(" Enter an integer and press 'enter':\n");
        scanf("%d" , &d);
        printf(" Enter the desired base and press 'enter':\n");
        scanf("%d" , &b);

        if (b < 2) {

                printf(" Your base is to low! \n")
        } else {

                while (d != 0) {

                        int radix;
                        radix = d % b;
                        d = d / b;
                        char basechars[] = "0123456789ABCDEF";

                        printf("%c" , basechards[radix]);
                }
        }
        return 0;
}

This Program prompts the user for a decimal and a base to convert that decimal to the base that has been chosen. The conversion is however printed in reverse order and I need it to print regular. Example: Entered: 112, then entered 16, result is 07 rather than 70.


回答1:


You can store each digit in an array:

} else {
    char arr[32];
    int counter = 0;
    while (d != 0) {
        int radix;
        radix = d % b;
        d = d / b;
        char basechars[] = "0123456789ABCDEF";
        arr[counter++] = basechars[radix];
    }
    if (counter == 0)
        arr[counter++] = '0';
    arr[counter++] = '\0';
    print_rev(arr);
    printf("\n");
}

and then print the string using a recursive function (it will reverse the output):

void print_rev(const char *s)
{
    if (*s) {
        print_rev(s + 1);
        printf("%c", *s);
    }
}

or directly:

} else {
    char arr[32];
    int counter = 0;
    while (d != 0) {
        int radix;
        radix = d % b;
        d = d / b;
        char basechars[] = "0123456789ABCDEF";
        arr[counter++] = basechars[radix];
    }
    if (counter == 0) {
        printf("0");
    else {
        while (counter--)
            printf("%c", arr[counter]);
    }
    printf("\n");
}



回答2:


  1. Reversing the array is the most straightforward way.
  2. Use the limit.h macro LONG_BIT to know the maximum needed characters to store. This sizes your array.
  3. I'm also checking the base for the upper limit of 16.
  4. Build the array, then print it. Note it handles 0 just fine.
  5. You also forgot negative numbers.

    } else if (b > 16) {
        printf(" Your base is too high! \n");
    } else {
        const char basechars[] = "0123456789ABCDEF";
    
        char arr[LONG_BIT];  // d is an integer, so LONG_BIT holds
                     // enough characters for a binary representation.
        int counter = 0;
        int negative_flag = 0;
    
        if (d < 0) {
            d = -d;
            negative_flag = 1;
        }
    
        do {
            int digit = d % b;
            d = d / b;
    
            arr[counter++] = basechars[digit];
         } while (d != 0);
    
         if (negative_flag) {
            printf ("-");
         }
    
         while (counter--) {
             printf ("%c", arr[counter]);
         }
         printf ("\n");
     }
    



回答3:


This version does dynamic memory allocation so that you don't have to specify how long the converted string has to be beforehand.

The numbers can be as large as you please, especially important in binary conversion. I also put a check for base 16, which is the upper limit.

int main (void)
{

        int d, b, c, i = 1;
        char *converted = malloc(i);
        printf(" Enter an integer and press 'enter':\n");
        scanf("%d" , &d);
        printf(" Enter the desired base and press 'enter':\n");
        scanf("%d" , &b);

        if (b < 2) {

                printf(" Your base is to low! \n");
                return 1;

        } else if (b > 16) {

                printf(" Your base is to high! \n");
                return 1;

        } else {

                while (d != 0) {

                        int radix;
                        radix = d % b;
                        d = d / b;
                        char basechars[] = "0123456789ABCDEF";
                        converted = realloc(converted, i++);
                        *(converted +i - 1) = basechars[radix];

                }
        }
    i--;
    while(i != 0) {
        printf("%c", converted[i]);
        --i;
    }
    free(converted);
    printf("\n");

    return 0;
}    



回答4:


Offer a recursive approach.

Determine if additional chars need to be printed from the more significant digits, recursively call the helper function and then print the numbers least significant digit.

Code should take care to handle "0" as a valid input. The below uses negative values to well handle INT_MIN.

static void PrintDigits(int x, int base) {
  static const char basechars[] = "0123456789ABCDEF";
  if (x <= -base) {
    PrintDigits(x/base, base);
  }
  putchar(basechars[-(x%base)]);
}

void PrintInt(int x, int base) {
  if (base < 2 || base > 16) {
    printf(" Your base is out of range! \n");
  } else {
    if (x < 0) putchar('-');
    else x = -x;
    PrintDigits(x, base);
  }
  putchar('\n');
}

int main(void) {
  PrintInt(65535, 16);
  PrintInt(65535, 10);
  PrintInt(65535, 2);
  PrintInt(INT_MAX, 10);
  PrintInt(0, 10);
  PrintInt(-1, 16);
  PrintInt(INT_MIN, 10);

  int d, b;
  printf(" Enter an integer and press 'enter':\n");
  scanf("%d" , &d);
  printf(" Enter the desired base and press 'enter':\n");
  scanf("%d" , &b);
  PrintInt(d, b);
  return 0;
}

FFFF
65535
1111111111111111
2147483647
0
-1
-2147483648

Even with base 2, recursion depth would be no more than the bit width of int.



来源:https://stackoverflow.com/questions/28862850/how-to-print-character-array-in-reverse-order-of-c-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!