In my code I am required to be able to convert any integer input to a desired base between 2 and 16. The problem is though the output states my code runs successfully, i get no output. I have tried in NetBeans and a linux terminal. My code is shown below:
/*
* File: main.c
* Author: Tyler Weaver
* Assignment 1: Takes a decimal value and converts it to a desired base
*
* Created on October 11, 2014, 11:57 PM
*/
#include <stdio.h>
void toBase(unsigned decimal, unsigned base, char *newNum);
int main(int argc, char** argv) {
const int MAX_LEN = 32;
char newNum[32];
unsigned decimal, base;
printf("Enter a decimal value followed by a desired base: ");
scanf(" %u", &decimal);
scanf(" %u", &base);
toBase(decimal, base, newNum);
printf("%u equals ", decimal);
//Print the array out in reverse order
unsigned count;
for (count = 0; count != '\0'; count++);
for (count--; count >= 0; count--) {
printf("%c", newNum[count]);
}
printf(" (base-%u)\n", base);
return 0;
}
/**
* Converts a number to desired base
* @param decimal the number which to convert
* @param base the base to convert decimal to
* @param newNum the character array which to store the conversion
*/
void toBase(unsigned decimal, unsigned base, char *newNum) {
const unsigned ASCII_DIFF = 97;
char *p;
for (p = newNum; decimal > 0; p++) {
unsigned temp = decimal % base;
*p = (temp < 10) ? temp : ((char) temp - 10 + ASCII_DIFF);
}
}
My output in NetBeans:
Enter a decimal value followed by a desired base: 6 4
RUN SUCCESSFUL (total time: 1s)
It appears the same on the linux terminal as well. I have tried placing printf statements after the scanf statements but those do not appear either. Any information would be helpful.
You seem to be running into an infinite loop inside the toBase function.
void toBase(unsigned decimal, unsigned base, char *newNum) { const unsigned ASCII_DIFF = 97; char *p; for (p = newNum; decimal > 0; p++) { unsigned temp = decimal % base; *p = (temp < 10) ? temp : ((char) temp - 10 + ASCII_DIFF); } }
You use
decimal > 0 as a condition, but you never modify the value of decimal inside the loop.
Because of this, all code written after the toBase() function call never gets executed.
Side note : I'm a little bothered by the "RUN SUCCESSFUL (total time: 1s)". Compiling this code with GCC and running it gives me a segmentation fault. Combined with the infinite loop issue, I highly doubt that the program has been ended "successfully".