3
\$\begingroup\$

I was creating a program and I was trying to explain it to some of my coding friends. They commented that it was too tedious typing out all the "if" commands. How do I streamline this code?

Note: this is a ".bat" program.

Waiter.bat

@echo off
set /p Food="What would you like to eat? "
if /i %Food%==pizza findstr "Pizza" Menu.txt
if /i %Food%==bread findstr "Bread" Menu.txt
if /i %Food%==macaroni findstr "Macaroni" Menu.txt
pause

Using the user input, the batch file looks inside Menu.txt and then it echos that description for that one food item.

Menu.txt

Pizza | Flattened dough, layered with tomato sauce, cheese, and choice of toppings.
Bread | Dough that has been baked.
Macaroni | Macaroni pasta with cheese.
asked Feb 23, 2015 at 21:45
\$\endgroup\$
0

1 Answer 1

4
\$\begingroup\$

With the help of a Windows user in chat (Thank's Simon!), we've got a much better solution figured out:

@echo off
set /p Food="What would you like to eat? "
set "Food=%Food% |"
findstr /C:"%Food%" Menu.txt
pause

This will concatenate the pipe character to the end of the user-entered string and find the line that begins with that literal string.

Ordinarily, findstr expects a space delimited list of words to search for. Using the /C: flag will look for the literal string rather than breaking the string up into separate strings and finding each individual word.

As long as your Menu.txt file maintains the format "MenuItem | Description", this .bat file will work and you won't have to edit it each time you edit your menu.

You just have to keep the formatting and don't put the pipe character anywhere else in the file.

answered Feb 23, 2015 at 23:50
\$\endgroup\$
1
  • \$\begingroup\$ Thanks! It is way easier than writing out every "if" command. \$\endgroup\$ Commented Feb 23, 2015 at 23:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.