The output you expect differs from the output you get in two aspects:
- The phrases "first" and "second" are not in mathmode.
- The macro
\printmylist
does not deliver the output 1: one \\ 2: four \\
.
Besides this you don't need \makeatletter
and \makeatother
with the definition of the \printmylist
-macro as that definition does not contain the symbol "@".
Also the definition of your \addtomylist
-command will contain space tokens that might produce horizontal space.
Here comes your code with slight modifications. I hope it now does what you wish it to do:
\documentclass[a4paper,10pt]{report}
\setlength{\parindent}{0pt}
\newcounter{Mynumbers}
\newcommand*\printmylist{}
\makeatletter
\newcommand{\addtomylist}[2]{%
\stepcounter{Mynumbers}%
$^{(\theMynumbers,#1) }~$%
\expandafter\g@addto@macro\expandafter\printmylist\expandafter{\number\value{Mynumbers}: #2 \\}%
}%
\makeatother
\begin{document}
$first$\addtomylist{0}{one}\\
$second$\addtomylist{4}{four}\\
\printmylist\\
\hrulefill\\
expected output:\\
$first^{(1,0)}$\\
$second^{(2,4)}$ \\
1: one \\
2: four \\
\end{document}
You might get better results using \ensuremath
instead of $..$
.
You might get better results either using \par
instead of \\
or wrapping things into \hbox
es while via \par
ensuring that TeX is in vertical mode where each outermost \hbox
is treated a s a single line:
\documentclass[a4paper,10pt]{report}
\setlength{\parindent}{1cm}
\newcounter{Mynumbers}
\newcommand*\printmylist{\par}
\makeatletter
\newcommand{\addtomylist}[2]{%
\stepcounter{Mynumbers}%
\ensuremath{^{(\theMynumbers,#1)}}%
\expandafter\g@addto@macro
\expandafter\printmylist
\expandafter{%
\expandafter\hbox
\expandafter{%
\number\value{Mynumbers}: #2}}%
}%
\makeatother
\begin{document}
\verb|\parindent| is set to 1cm so you can see the difference between \TeX{}
acting in horizontal mode (where it also does the horizontal line-indenting with
the first line of a paragraph and the line breaking within a paragraph and the
\verb|\parfillskip|-glue-thingie at the end of a paragraph) and \TeX{} acting
in vertical mode where each outermost \verb|\hbox| is treated as a single
"line" whose content in turn gets processed in restricted horizontal mode:
\noindent\hrulefill
received output:
$first\addtomylist{0}{one}$
$second\addtomylist{4}{four}$
\printmylist
\noindent\hrulefill
expected output:
$first^{(1,0)}$
$second^{(2,4)}$
\hbox{1: one}
\hbox{2: four}
\end{document}
first$^{(1,0)}$ second$^{(2,4)}$
, but I think that this is what you intended). What error are you getting? Also, I am not sure if this is an accident or an artifact of your cutting it down to a MWE, but\addtomylist
ignores#2
.\\
at the end of a paragrah (it makes terrible output and tex warns about badness 10000 (which is the maximum badness possible)