TikZ-PGF – Using \Alph on \foreach Loop Argument

foreachloopstikz-pgf

Here's basically what I try to do:

\begin{tikzpicture}
  \foreach \x in {1,2,3,4,5}
  {
    \draw (\x,1) node{\Alph{\x}};
  }
\end{tikzpicture}

However if I do that, I get

ERROR: Missing number, treated as zero.

I tried to prefix the number with \the:

\begin{tikzpicture}
  \foreach \x in {1,2,3,4,5}
  {
    \draw (\x,1) node{\Alph{\the\x}};
  }
\end{tikzpicture}

and got:

ERROR: You can't use `the character 1' after \the.

After searching around on TeX.SE, I thought the following solution should work:

\begin{tikzpicture}
  \foreach \c [count=\x] in {{A},{B},{C},{D},{E}}
  {
    \draw (\x,1) node{\c};
  }
\end{tikzpicture}

However that got me an error that \x is not defined.

So, how do I get the desired result?

Best Answer

\Alph expects as its argument a counter name; in your case LaTeX looks for the inexistent counters named 1, 2 and so on.

A way out is to use the internal command that transforms numbers to letters, that is \@Alph:

\makeatletter
\newcommand{\myAlph}[1]{\expandafter\@Alph#1}
\makeatother

\begin{document}
\begin{tikzpicture}
  \foreach \x in {1,2,3,4,5}
  {
    \draw (\x,1) node{\myAlph{\x}};
  }
\end{tikzpicture}
\end{document}

Alternatively, the more esoteric

\newcommand{\myAlph}[1]{\char\numexpr`A-1+#1\relax}

will do the same, but is quite different from the other one in that the former leaves the letters in the input stream. while the latter leaves the instructions to print the letters.

Related Question