立即展开 `ifthenelse`

立即展开 `ifthenelse`

考虑这个脚本:

\documentclass{report}
\usepackage{ifthen}
\newcommand{\thesissize}{SHORT}
\begin{document}
   \setcounter{page}{
    %3
    \ifthenelse{
    \equal{\thesissize}{SHORT}
    }{3}{2}
  }
  hey
\end{document}

编译此脚本会出现错误:

! Missing number, treated as zero.

我怀疑这是由于\ifthenelse在执行时未进行评估造成的\setcounter。我该如何解决这个问题?

答案1

你不能\ifthenelse在 inside使用\setcounter。更改顺序:

\documentclass{report}
\usepackage{ifthen}
\newcommand{\thesissize}{SHORT}
\begin{document}
   \ifthenelse{\equal{\thesissize}{SHORT}}
    {\setcounter{page}{3}}{\setcounter{page}{2}}


  hey
\end{document}

expl3使用和可以进行可扩展测试etoolbox。对于这两者,您都应该将参考文本存储在命令中:

\documentclass{report}
\usepackage{expl3,etoolbox}
\newcommand{\thesissize}{SHORT}
\newcommand{\shortsize}{SHORT}

\begin{document}
\ExplSyntaxOn
\setcounter{page}{\tl_if_eq:NNTF\thesissize\shortsize{3}{2}}
\ExplSyntaxOff

\setcounter{page}{\ifdefequal{\thesissize}{\shortsize}{3}{2}}

  hey
\end{document}

答案2

使用 pdfTeX 宏进行字符串比较的另一个版本\pdfstrcmp。下面使用该pdftexcmds包使其可供同名的所有引擎使用:

\documentclass[]{article}

\usepackage{pdftexcmds}
\makeatletter
\newcommand\ifstreq[2]
  {%
    \ifnum\pdf@strcmp{#1}{#2}=0
  }
\makeatother

\newcommand\thesissize{SHORT}

\begin{document}
\setcounter{page}{\ifstreq{\thesissize}{SHORT}3\else2\fi}
hey
\end{document}

如果首选 LaTeX 语法,则可以使用

\documentclass[]{article}

\usepackage{pdftexcmds}
\makeatletter
\newcommand\ifstreq[2]
  {%
    \ifnum\pdf@strcmp{#1}{#2}=0
      \expandafter\@secondofthree
    \fi
    \@secondoftwo
  }
\providecommand\@secondofthree[3]{#2}
\makeatother

\newcommand\thesissize{SHORT}

\begin{document}
\setcounter{page}{\ifstreq{\thesissize}{SHORT}{3}{2}}
hey
\end{document}

答案3

没有包裹。

\documentclass{report}
\newcommand{\thesissize}{SHORT}
\begin{document}

\newcommand\tmp{SHORT}
\ifx\tmp\thesissize\relax\setcounter{page}{3}\else\setcounter{page}{2}\fi

\thepage

\renewcommand\tmp{NOT SHORT}
\ifx\tmp\thesissize\relax\setcounter{page}{3}\else\setcounter{page}{2}\fi

\thepage
\end{document}

在此处输入图片描述

可扩展版本:

\documentclass{report}
\newcommand{\thesissize}{SHORT}
\begin{document}

\newcommand\tmp{SHORT}
\setcounter{page}{\ifx\tmp\thesissize3\else2\fi}

\thepage

\renewcommand\tmp{NOT SHORT}
\setcounter{page}{\ifx\tmp\thesissize3\else2\fi}

\thepage
\end{document}

相关内容