0

Been racking my brain on this problem, not sure what I'm doing wrong. This code is highly based off of this solution but something isnt clicking. The goal is to be able to reference the contents of the solution environment later in my code.

Here is what im working with:

\documentclass[addpoints,12pt]{exam}
\usepackage{environ}

\makeatletter
\NewEnviron{sol}{
\begin{solution}
\def\@currentlabel{\BODY}\label{solt:\thequestion}
\BODY
\end{solution}
}
\makeatother


\begin{document}
\begin{questions}
\question This is a question

\begin{sol}
My solution
\end{sol}

\begin{choices}
\choice 8
\choice 1
\choice 3
\choice 4
\end{choices}

\end{questions}


The first solution is:\\
\ref{solt:1}

\end{document}

When I run this, I receive an invalid reference. Any pointers as to what i may be doing incorrectly?

1
  • That was my bad. I've updated the post with the complete code. Yes i would like to generate the entire solution. In this case, it should display "My solution". Mar 8, 2020 at 14:58

1 Answer 1

1

The solution is not typeset so your label is never generated in the .aux file, I think you intended

\documentclass[addpoints,12pt]{exam}
\usepackage{environ}

\makeatletter
\NewEnviron{sol}{%
\def\@currentlabel{\BODY}\label{solt:\thequestion}%
\begin{solution}%
\BODY
\end{solution}%
}
\makeatother


\begin{document}
\begin{questions}
\question This is a question

\begin{sol}
My solution
\end{sol}

\begin{choices}
\choice 8
\choice 1
\choice 3
\choice 4
\end{choices}

\end{questions}


The first solution is:\\
\ref{solt:1}

\end{document}

However using an a \label with an automatically generated key seems dangerous, any edit to the file will mean the question gets a new number so the \ref will then refer a different question with no warning. It would be more in the spirit of \label/\ref to give your sol environment an argument so you supply a name to use in the \label which you could then also use in \ref.

1
  • Thank you!! Ill definitely switch up the labeling too Mar 8, 2020 at 20:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .