将命令嵌入带有参数的环境和环境中

时间:2016-08-02 11:31:14

标签: latex

我对乳胶很新,我正在尝试为考试问题创建一种格式,以便尽可能少写乳胶。 目前我写了这段代码:

\documentclass{article}

%the question environment wrapping every exam questions
\newenvironment{q}[2] {
    \newcounter{answerCounter} %used for display of answer number with question
    \setcounter{answerCounter}{0}
    \newcommand{a}[1] {
            \item a\value{answerCounter}: ##1 
            %I used double hyphen on previous line because i'm within an environment
            \addtocounter{answerCounter}{1}
    }

    \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}

我希望它能显示出来:

enter image description here

但是当我pdflatex exam.tex时,我得到以下前两个错误(还有更多,但我不想让你充满信息):

! 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}

? 

我是否错误地调用/定义了我的环境和命令?感谢。

1 个答案:

答案 0 :(得分:1)

以下是需要考虑的事项:

  1. 使用名称定义环境,如\newenvironment{someenv}中所示,而命令是使用其控制序列定义的,如\newcommand{\somecmd}中所示。请注意\。这是您的代码的主要问题。

  2. LaTeX定义了许多单字符控制序列,通常用于符号的重音符号。在更正上述(1)的示例后,已定义\a。相反,定义更具描述性的内容以提高代码可读性。

  3. 您可能会在代码中插入一些虚假空格。通过%的战略性展示位置可以阻止这些问题。请参阅What is the use of percent signs (%) at the end of lines?

  4. 在其他命令(如新计数器)中定义命令可能会导致问题,或者使事情变得不必要地变慢(在较大的文档和使用中)。而是在环境中定义外部 - 在全局范围内 - 然后根据需要重置数字。

  5. enter image description here

    \documentclass{article}
    
    \newcounter{answerCounter} %used for display of answer number with question
    %the question environment wrapping every exam questions
    \newenvironment{question}[2] {%
      \setcounter{answerCounter}{0}%
      \newcommand{\ans}[1]{%
        \stepcounter{answerCounter}%
        \item a\theanswerCounter: ##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}