3

I have different counters, and I want to increment them. After I do not want to increment them separately, I wanted to write a macro which does that for me, depending on the input. I have the following code:

\documentclass[10pt,a4paper]{book}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{tikz}
\usepackage{tocloft}

\newcounter{countera}
\newcounter{counterb}
\newcommand{\toC}[1]{
    \stepcounter{%
        \expandafter\csname counter#1\endcsname%
        }
}
\begin{document}
\toC{a}
\end{document}

When I now want to increment counter countera, I just want to call \toC{a} instead of \stepcounter{countera}. By using the code above, I get a lot of errors, such as ! Missing \endcsname inserted., ! Extra \endcsname. and ! LaTeX Error: No counter '\countera ' defined. The macro \toC{} will be expanded later, thus I would prefer to keep its structure like this, if possible. Why do I get those errors?

1
  • There's no need to use \csname counter#1\endcsname here Commented Apr 9, 2016 at 13:33

1 Answer 1

3

Do you mean this?

\documentclass[10pt,a4paper]{book}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{tikz}
\usepackage{tocloft}

\newcounter{countera}
\newcounter{counterb}
\newcommand{\toC}[1]{%
  \stepcounter{%
    counter#1%
  }
}
\begin{document}
\toC{a}
\toC{b}

\thecountera

\thecounterb

\end{document}
3
  • Thanks! Can you maybe also include how to use \thecounter#1 directly afterwards? Furthermore I had to notice that the % are absolutely necessary here, otherwise I get errors... Commented Apr 9, 2016 at 13:41
  • Problem solved, had to use \expandafter\csname thecounter#1\endcsname% there. Commented Apr 9, 2016 at 13:51
  • @arc_lupus: Ok, you solved it, but \csname thecounter#1\endcsname wasn't in your question anyways;-) Commented Apr 9, 2016 at 14:27

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.