I keep getting garbage characters when I am outputing "123" and "0".
I was able to narrow it down to the baseout method, and I believe it may be one of my "for loop" conditions but I can't seem to get to be able to remove the garbage characters.
If you can help, please do. Program is in C.
Thank you in advance.
#include <stdio.h>
#define COUNT 8 /* number of hex digits to display */
#define DECIMAL 10 /* to indicate base 10 */
#define HEX 16 /* to indicate base 16 */
/* array used for ASCII conversion */
const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
void baseout (int number, int base, FILE * stream) {
int f1;
int f2;
int index = 0;
int result = number;
char store1[f2];
/*This condition outputs the digit "0" on Line 4*/
if (number == 0) {
fputc(digits[0], stream);
}
/*This condition outputs the digit "0" after "0x"*/
if (base != DECIMAL){
store1[f1] = '0';
fputc(store1[f1], stream);
}
/*This condition outputs codes from bases 2-36*/
if (number != 0) {
for(f2 = 1; f2 < COUNT && result != 0; f2++){
index = result % base;
store1[f2] = digits[index];
result = result / base;
}
}
for (f2 = COUNT; f2 > 0; f2--){
fputc(store1[f2], stream);
}
}
void decout (unsigned int number, FILE * stream) {
/*Passes DECIMAL to baseout algorithm*/
baseout(number, DECIMAL, stream);
}
void hexout (unsigned int number, FILE * stream) {
/* Output "0x" for hexidecimal. */
writeline ("0x", stream);
baseout (number, HEX, stream);
}
void newline (FILE * stream) {
/* Output a newline character */
fputc('\n', stream);
}
int writeline (const char * message, FILE * stream) {
int index = 0;
/*While "index<messagelength" output the each character of message*/
while(message[index] != '\0'){
fputc(message[index], stream);
index++;
}
/*Return the message length*/
return sizeof(message);
}
int main (int argc, char *const* argv) {
writeline ("Hello World", stdout);
fprintf (stderr, "Hola Mundo\n");
newline(stdout);
decout (123, stdout);
newline(stdout);
decout (0, stdout);
newline(stdout);
hexout (0xFEEDDAD, stdout);
newline(stdout);
return 0;
}
The Desired Output is:
Hola Mundo
Hello World
123
0
0x0FEEDDAD
The Current Output is:
Hola Mundo
Hello World
123
0123
0x0FEEDDAD
This block of code is not well thought out.
for(f2 = 1; f2 < COUNT; f2++){
if (result != 0){
index = result % base;
store1[f2] = digit[index];
result = result / base;
}
}
You are incrementing f2
even after result
is 0
and not setting the value of store1[f2]
for those values. Then you go ahead and try to print the contents of store1
. Since store1
is not initialized to anything sensible, you are getting garbage.
Here's one way to fix those problems.
/*This condition outputs codes from bases 2-36*/
if (number != 0) {
for(f2 = 1; f2 < COUNT && result != 0; f2++){
index = result % base;
store1[f2] = digits[index];
result = result / base;
}
}
for (f2--; f2 > 0; f2--){
fputc(store1[f2], stream);
}