X140Yu
2/15/2016 - 1:56 PM

reverse_int.c

/*
 * reverse_int.c
 *
 *
 * Read an integer from stdin, reverse it,
 * and print if back to the user.
 */

#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>

#define BUFFERSIZE 20

/*
 calculate the length of the string
 */
int get_string_length(char *str);

/*
  reverse a string
  str: the string to reverse
  returns: the string reversed
 */
char * reverse_string(char *str);

int main(int argc, char *argv[])
{
    int input_ch;
    char buffer[20];

    // promote user to input
    printf("Enter a number to reverse: ");
    int len = 0;
    int is_negative = 0;

    // if it is a negative number
    input_ch = getchar();
    if (input_ch == '-') {
        is_negative = 1;
        input_ch = getchar();
    } else if (input_ch == '\n') {
        // there no digits to be process
        printf("Error: no digits have been read.\n");
        return EXIT_FAILURE;
    }

    // get user input from stdin
    do {
        if(!isdigit(input_ch)) {
            // not an integer, exit
            printf("Error: non-digit character entered\n");
            return EXIT_FAILURE;
        }
        buffer[len++] = input_ch;
    } while ((input_ch = getchar()) != '\n');

    // one char doesn't need reverse
    if(len == 1) {
        printf("%c\n", buffer[0]);
        return EXIT_SUCCESS;
    }


    // negative number should add '-' ahead
    if(is_negative) {
        printf("-%s\n", reverse_string(buffer));
    } else {
        printf("%s\n", reverse_string(buffer));
    }


    return EXIT_SUCCESS;
}

int get_string_length(char *str)
{
    int length = 0;
    while(*str != '\0') {
        str++;
        length++;
    }

    return length;
}

char * reverse_string(char *str)
{
    char *head = str;
    char *tail = &str[get_string_length(str) - 1];
    char temp;


    while(tail > head) {
        temp = *head;
        *head = *tail;
        *tail = temp;

        head++;
        tail--;
    }


    // get rid of the '0' ahead
    head = str;
    while(*head == '0') {
        head++;
    }

    return head;
}