Files
yait/input.c
2025-11-12 22:09:34 -05:00

71 lines
1.1 KiB
C

/* input.c
*
* Various input routines
*
* written by vx-clutch
*/
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "input.h"
char *getstring(char *fmt, ...) {
va_list args;
va_start(args, fmt);
printf("? ");
vprintf(fmt, args);
putc(' ', stdout);
va_end(args);
fflush(stdout);
char *buf = NULL;
size_t size = 0;
ssize_t len = getline(&buf, &size, stdin);
if (len < 0) {
free(buf);
return NULL;
}
if (len > 0 && buf[len - 1] == '\n')
buf[len - 1] = '\0';
return buf;
}
int yesno(char *fmt, ...) {
char prompt[256];
va_list ap;
va_start(ap, fmt);
vsnprintf(prompt, sizeof prompt, fmt, ap);
va_end(ap);
char buf[64];
for (;;) {
fprintf(stderr, "? %s", prompt);
fputs(" (y/n) ", stdout);
fflush(stdout);
if (!fgets(buf, sizeof buf, stdin))
return 0;
size_t i = 0;
while (buf[i] && isspace((unsigned char)buf[i]))
i++;
if (!buf[i])
continue;
char c = tolower((unsigned char)buf[i]);
if (c == 'y')
return 1;
if (c == 'n')
return 0;
}
}