Some problem with listings and C++

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?

• 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

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}},%
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}


• 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
\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},
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}


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