💾 Archived View for oakc.smol.pub › chooser-c captured on 2023-12-28 at 15:14:30. Gemini links have been rewritten to link to archived content
-=-=-=-=-=-=-
"Chooser" was a program written for the presentation on Windows Command-line usage, to show how to use an external command. It's simply a more powerful equivalent of choice.com.
Post containing the rest of the content from the presentation.
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (int argc, char **argv) { if (argc<2 || (argc==2 && strcmp(argv[1],"/?")==0)) { printf("Chooser\nUsage:\n %s <Choice1> [<Choice2> [<Choice3> [<Choice4>]]]\n",argv[0]); return 0; } int i; printf("Choose (1 to %d):\n",argc-1); for (i=1;i<argc;i++) { printf(" %d:\t%s\n",i,argv[i]); } char inp[355]; do { if (fgets(inp,255,stdin)!= NULL) { i = atoi(inp); } if (i<1 || i>=argc) fprintf(stderr,"Choose from 1 to %d!\n",argc-1); } while (i<1 || i>=argc); return i; }
We have made an improved equivalent of the “choice” command program since choice is sometimes not available and is very simplistic when it is. To get it, download the file “chooser.exe” from the given link and place it in the same folder as you have been saving your batch files in.
Use it by typing:
chooser "Choice 1" "Choice 2" "Choice 3"
Any number of choices can be specified (as long as they are specified in speech-marks if they include a space) and when run, the user will be greeted with the following:
Choose (1 to 3): 1: Choice 1 2: Choice 2 3: Choice 3
The user will type a number representing their chosen choice (and press enter as the number can be multiple digits) and this number will be used to set the ERRORLEVEL (if something else is typed then the user will be asked again).
You can use this to replace “choice” in “Dinner.bat”:
@echo off :Question echo Do you want dinner yet? chooser Yes No "I'll go hungry" if ERRORLEVEL 3 goto Eat if ERRORLEVEL 2 goto No echo OK, I will serve it in a minute. goto Exit :Eat echo You have to eat something! Goto Question :No echo I see that you do not. :Exit pause
This version names the choices and gives a third option of going hungry, which, when selected, tells the user that they must eat something and then asks the question again.