[Tex/LaTex] Macro parameter character in \input file

macros

I would like to include some paragraphs from external .tex files in my document, very similar to what \lipsum does. As far as I understood it until now is using \input equivalent to directly typing text and commands.

However, when running the MWE below

\begin{filecontents}{myTextFile.tex}
\ifthenelse{#2=1}{first paragraph}{}
\ifthenelse{#2=2}{second paragraph}{}
\end{filecontents}

\documentclass{report}
\usepackage{ifthen}
\newcommand\myParagraphs[2]{\input{#1}}

\begin{document}
\myParagraphs{myTextFile.tex}{2}
\end{document}

I get the error message

You can't use `macro parameter character #' in horizontal mode.

Thus, '#2' is not known in myTextFile.tex. How can I make #2 known there, or is there an easier way to define \myParagraphs{<file>}{<paragraph no>}

Best Answer

You can't do like that. The definition of \myParagraphs doesn't use #2; so

\myParagraphs{myTextFile.tex}{2}

becomes

\input{myTextFile}

and so TeX reads your file, where #2 is illegal. Here's a way: define a temporary macro to expand to the value of #2:

\begin{filecontents}{myTextFile.tex}
\ifthenelse{\second=1}{first paragraph}{}
\ifthenelse{\second=2}{second paragraph}{}
\end{filecontents}

\documentclass{report}
\usepackage{ifthen}
\newcommand\myParagraphs[2]{\def\second{#2}\input{#1}}

\begin{document}
\myParagraphs{myTextFile.tex}{2}
\end{document}
Related Question