[Tex/LaTex] Using \input{} inside caption

captionsinput

I am wondering why I am getting errors when I try to add a caption to table using the \input command. A minimal example is as follows. The file cap2test.tex can be any text file. E.g., mine contains only the characters “The first three''

\documentclass{article}
\begin{document}
\begin{table}
\caption{\input{cap2test.tex}}
\begin{tabular}{c}
asd
\end{tabular}
\end{table}
\end{document}

The error is probably going to be the same for other people:

./test.tex:4: Argument of \@caption has an extra }.

\par
l.4 \caption{\input cap2test.tex}

I'll also add that I have had such errors for years, and usually worked around it by not modularizing my tables or figures this way. Is it a bug?

Nicolae

Best Answer

A non-robust macro -- or "fragile" macro, to use LaTeX jargon -- in the argument of a \caption command will throw this error. Non-robust commands inside the argument of \caption must be \protected to avoid getting an error message. You should therefore write

\caption{\protect\input{cap2test.tex}}