You are here:

C++/Create/Print formatted Ascii Table

Advertisement


Question
I am trying to create and print the ASCII Table on a little card or at least send it to a file.  I am currently running a loop from 0 to 127 and using fprintf to send the data to a text file.  Each loop using the format specifiers for hex, char, dec and I also need it to show binary and oct.  It is not formatted correctly and needs to have each set of values on individual lines with headers and columns.  What is the best way to accomplish this?  I have included my code so you can see what I have tried to do so far.

int main(dec)
{
   FILE * table;
   table = fopen("c:table.txt", "wb");
   
   fprintf(table, "%s", "Decimaltt");
   fprintf(table, "%s", "Hexadecimaltt");
   fprintf(table, "%s", "Characterrr");

   for (int i = 0; i <= 127; i++)
   {
       fprintf(table, "%dt", i);
       fprintf(table, "%xt", i);
       fprintf(table, "%ct", i);
       fprintf(table, "%ooorr", i);
   }
  return 0;
}

Answer
April, I think something was lost in the post - it seems like you had backslash t in the post to use a tab to spread things out.  If I'm right, this is OK and works, but, you've got printf, which can format to specified widths, so let's use that.

fprintf( table, "%12s %12s %12s %12s\r\n", "Decimal", "Hexadecimal", "Character", "Octal" );

Inside the for loop, use the same padding specifier:

"%12d %12x %12c %12o\r\n"

I also see the file is opened in binary "wb".  I would open as a "wt" (text) and use just \n.  The compiler library for the intended OS should get the line endings right.  Or, as I do out of habit, use \r\n to ensure at least a Windows compatible file.

Bill

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Bill A

Expertise

I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.

Experience

I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Publications
Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

Education/Credentials
BS Computer Engineering

©2016 About.com. All rights reserved.