1

I have to insert a C++ code in a .tex file but I want that is written with the text coloured like in the C++ program. If I use lstlisting there is the C++ program but in b/w. Any idea?

  • 3
    Welcome to TeX.SX! You need a coloring style -- the style depends on your own decisions of course – user31729 Dec 25 '15 at 10:03
3

The style is basically the some as given in the listings manual.

listings uses several substyles for keywords, strings, identifiers, comments, each one is basically called ....style which can set to be 'anything' either in \lstset or in the optional argument of the lstlisting environment.

In addition, it's possible to define personal styles as a short-hand and use it with the style=... option. \lstdefinestyle{style name}{key=value list} defines such a style.

\documentclass{article}
\usepackage[x11names]{xcolor}
\usepackage{listings}

\lstset{language=C++,
  basicstyle=\small, % print whole listing small
  keywordstyle=\color{black}\bfseries\underbar,
  % underlined bold black keywords
  identifierstyle={\color{red}},%
  commentstyle=\color{brown}, % brown comments
  stringstyle=\color{blue}\ttfamily, % typewriter type for strings, blue 
  showstringspaces=false
}


\begin{document}
\begin{lstlisting}
  #include <iostream>
  // Hello World - Example
  int main( int argc, char **argv )
  {
    std::cout << "Hello World\n";
    return 0;
  }
\end{lstlisting}
\end{document}

enter image description here

  • 1
    stringstyle=\color{\blue} should be stringstyle=\color{blue} – user2478 Dec 25 '15 at 10:47
  • @Herbert: Yes, thank you. I've changed on disk and later on here, without copying. Stupid typo. – user31729 Dec 25 '15 at 10:48
2
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[scaled=0.84]{beramono}
\usepackage[utf8]{inputenc}
\usepackage[x11names]{xcolor}
\usepackage{listings}
\lstnewenvironment{CPP}
 {\lstset{language=C++,
    basicstyle=\small\ttfamily,
    keywordstyle=\bfseries,
    identifierstyle=\color{red},
    commentstyle=\color{brown},
    stringstyle=\color{blue},
    tabsize=2,
}}{}

\begin{document}
\begin{CPP}
#include <iostream>
// Hello World - Example
int main( int argc, char **argv )
    {
        std::cout << "Hello World\n";
        return 0;
    }
\end{CPP}
\end{document}

enter image description here

  • 1
    Code stealer :-P – user31729 Dec 25 '15 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.