Created
January 10, 2023 23:13
-
-
Save Leowbattle/dde0b3f9c929152233fa6c5834937f84 to your computer and use it in GitHub Desktop.
Basic printf implementation supporting strings and ints.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdarg.h> | |
| void fmt_int(char* buf, int n) { | |
| int i = 0; | |
| if (n < 0) { | |
| *buf++ = '-'; | |
| n = -n; | |
| } | |
| while (n > 0) { | |
| buf[i++] = (n % 10) + '0'; | |
| n /= 10; | |
| } | |
| for (int j = 0; j < i / 2; j++) { | |
| char tmp = buf[j]; | |
| buf[j] = buf[i - j - 1]; | |
| buf[i - j - 1] = tmp; | |
| } | |
| buf[i] = '\0'; | |
| } | |
| int my_printf(const char* format, ...) { | |
| va_list args; | |
| va_start(args, format); | |
| int n = 0; | |
| while (*format != '\0') { | |
| switch (*format) { | |
| case '%': | |
| format++; | |
| switch (*format) { | |
| case '%': | |
| putchar('%'); | |
| n++; | |
| break; | |
| case 's': | |
| char* s = va_arg(args, char*); | |
| while (*s != '\0') { | |
| putchar(*s); | |
| n++; | |
| s++; | |
| } | |
| break; | |
| case 'd': | |
| int d = va_arg(args, int); | |
| char buf[11]; | |
| fmt_int(buf, d); | |
| for (char* pbuf = buf; *pbuf != '\0'; pbuf++) { | |
| putchar(*pbuf); | |
| n++; | |
| } | |
| break; | |
| default: | |
| putchar('?'); | |
| n++; | |
| } | |
| break; | |
| default: | |
| putchar(*format); | |
| n++; | |
| } | |
| format++; | |
| } | |
| va_end(args); | |
| return n; | |
| } | |
| int main(int argc, char** argv) { | |
| my_printf("Hello %s %d\n", "world", 567); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment