Simonlbc - 1 year ago 154
LaTeX Question

# embedded commands into environments and environments with parameters

I'm pretty new to latex and I'm trying to create a format for exam questions that would make write as few latex as possible.
For the moment I wrote this code:

\documentclass{article}

%the question environment wrapping every exam questions
\newenvironment{q}[2] {
\newcommand{a}[1] {
%I used double hyphen on previous line because i'm within an environment
}

\item q#1: #2
%the 1st param of q (the environment) is the question number, 2nd is the question itself
\begin{itemize}
} { \end{itemize} }

\begin{document}

\begin{itemize}
\begin{q}{1}{to be or not to be?}
\a{to be}
\a{not to be}
\end{q}
\begin{q}{2}{are you john doe?:}
\a{No i'm Chuck Norris}
\a{maybe}
\a{yes}
\end{q}
\end{itemize}

\end{document}


and I want it to display this:

but when I do
pdflatex exam.tex
I get the following first 2 errors (there are more but I don't want to flood you with information):

! Missing control sequence inserted.
<inserted text>
\inaccessible
l.21         \begin{q}{1}{to be or not to be?}

?
(/usr/share/texlive/texmf-dist/tex/latex/base/omscmr.fd)

! LaTeX Error: Command \to be unavailable in encoding OT1.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
...

l.22                 \a{to be}

?


Have i called/defined my environments and commands wrongly? Thanks.

Here are some things to consider:

1. Environments are defined with a name, as in \newenvironment{someenv}, while commands are defined with their control sequence, as in \newcommand{\somecmd}. Note the \. This is the main problem with your code.

2. LaTeX defines a number of single-character control sequences, typically used for accents on symbols. After correcting your example for (1) above, \a is already defined. Instead, define something more descriptive to increase code readability.

3. You may have some spurious spaces inserted as part of your code. These are prevented with strategic placements of %. See What is the use of percent signs (%) at the end of lines?

4. Defining commands within other commands (like a new counter) could lead to problems, or make things unnecessarily slow (in larger documents and usage). Rather define the counter outside an environment - in the global scope - and then just reset the number as needed.

\documentclass{article}

%the question environment wrapping every exam questions
\newenvironment{question}[2] {%
\newcommand{\ans}[1]{%
%I used double hyphen on previous line because i'm within an environment
}

\item q#1: #2
%the 1st param of q (the environment) is the question number, 2nd is the question itself
\begin{itemize}
} { \end{itemize} }

\begin{document}

\begin{itemize}
\begin{question}{1}{To be or not to be?}
\ans{to be}
\ans{not to be}
\end{question}
\begin{question}{2}{Are you John Doe?}
\ans{No I'm Chuck Norris}
\ans{maybe}
\ans{yes}
\end{question}
\end{itemize}

\end{document}