Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

How to print character array in reverse order of C program

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

int main (void)
{

        int d, b, c;

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

        if (b < 2) {

                printf(" Your base is to low! 
")
        } 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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++] = '';
    print_rev(arr);
    printf("
");
}

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("
");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...