As some of you might know I've been working my way through the C Programming Language (2nd).
I recently finished a rough implementation of the itoa
exercise (chapter 3). It's important to note that we haven't been introduced to any advanced subjects like pointers, dynamic arrays etc yet.
The exercise is to create a string representation of a number with a left padding of spaces depending on a parameter width
. In my case the number is 1030 and the width is 10, meaning the representation is ______1030
(replace _
with ).
I also have decided to use as few external packages as possible so that I can learn more about C rather than knowing how to implement packages. This might be against some best practices so I thought it would be best to mention this before you get to my implementation.
I would like to get general feedback, constructive criticism on the solution and especially help with identifying any particular syntactical errors or potential bottlenecks. In this implementation I've decided to do one static test rather than allowing the user to input data.
I am especially interested in how I could possibly make the loop a bit more effective as I really don't like that I need to use a second statement to divide number
.
You can find my solution on Gist if you wish to have it formatted, or below:
/*
itoa.c (i, s, w)
@param i: integer
@param s: char []
@param w: width
@returns a string representation of i with any excess (left) padding
in blankspaces dependant on the width w.
*/
#include <stdio.h>
#include <math.h>
#define MAXLINE 100
unsigned numDigits(const unsigned n) {
if (n < 10) return 1;
return 1 + numDigits(n / 10);
}
void itoa(int number, char string_out [], int width) {
int i = width;
do {
string_out[i] = (number > 0) ? number % 10 + '0' : ' ';
number /= 10;
} while ((i--) != 0);
string_out[width + 1] = '\0';
}
int main () {
char str [MAXLINE];
if (numDigits(1030) > 10) {
printf("Sorry, the number you provided was longer than 10 characters\n");
return 1;
}
itoa(1030, str, 10);
printf("Before: %d\nAfter: %s\n", 1030, str);
return 0;
}
itoa(12345, string_out, 3)
do? Make"12345"
? How aboutitoa(12345, string_out, 300)
? oritoa(-12345, string_out, 10)
,itoa(12345, string_out, -10)
? \$\endgroup\$