Hello everyone,
I'm producing a piece of code that converts numbers to different bases. I want the program to loop until someone types in zero which exits the program. I have it setup and working, however I think there's a problem with the output. Since I'm using scanf() multiple times it seems to be tagging a newline char to the other calls, therefore producing bad output, at least I think. Anyways here's the code.
Code:
#include <stdio.h>
// functions
void getNumberAndBase(void);
void convertNumber(void);
void displayConversion(void);
void clear_line(void);
// globals
int gConvertedNumber[64], gBase, gDigit = 0;
unsigned long long gNumber;
int main(void) {
int stop = 1;
char ch;
while (stop == 1) {
//1. get the number and coversion base
getNumberAndBase();
if (gNumber == 0)
stop = 0;
else {
//2. convert the number by gathering it's digits
convertNumber();
//3. display the number
displayConversion();
}
}
return 0;
}
void getNumberAndBase(void) {
printf("Input number to convert: ");
scanf("%llu", &gNumber);
clear_line();
if (gNumber != 0) {
printf("Input conversion base: ");
scanf("%i", &gBase);
clear_line();
while (gBase < 2 || gBase > 16) {
printf("Error: no base, please input a proper base\n");
scanf("%i", &gBase);
clear_line();
}
}
}
void convertNumber(void) {
do {
gConvertedNumber[gDigit] = gNumber % gBase;
gDigit++;
gNumber /= gBase;
} while (gNumber != 0);
}
void displayConversion(void) {
static const char numTable[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
for (gDigit--; gDigit >= 0; gDigit--)
printf("%c", numTable[gConvertedNumber[gDigit]]);
printf("\n");
}
void clear_line(void) {
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
}
And output, (input text bolded)
Code:
OUTPUT:
Input number to convert: 10
Input conversion base: 2
1010
Input number to convert: 10
Input conversion base: 2
101 <--- Incorrect
Input number to convert: 0
If there's anyone that can clarify this for me or point me to a resource that explains this, that would be helpful. Thank you.