I'm trying to type my C++ homework by LaTeX in order to prepare it as a pdf file.
I want to have my keywords in blue, my numbers in violet and my strings in reddish brown. I could do the two first by looking up the documentation and other questions here, but I have no idea how to change the color of my strings.
\documentclass{article}
\usepackage{etoolbox}
\usepackage{xcolor}
\usepackage{listings}
\newtoggle{InString}{}% Keep track of if we are within a string
\togglefalse{InString}% Assume not initally in string
\newcommand*{\ColorIfNotInString}[1]{\iftoggle{InString}{#1}{\color{violet}#1}}%
\newcommand*{\ProcessQuote}[1]{#1\iftoggle{InString}{\global\togglefalse{InString}}{\global\toggletrue{InString}}}%
\lstset{literate=%
{"}{{{\ProcessQuote{"}}}}1% Disable coloring within double quotes
{'}{{{\ProcessQuote{'}}}}1% Disable coloring within single quote
{0}{{{\ColorIfNotInString{0}}}}1
{1}{{{\ColorIfNotInString{1}}}}1
{2}{{{\ColorIfNotInString{2}}}}1
{3}{{{\ColorIfNotInString{3}}}}1
{4}{{{\ColorIfNotInString{4}}}}1
{5}{{{\ColorIfNotInString{5}}}}1
{6}{{{\ColorIfNotInString{6}}}}1
{7}{{{\ColorIfNotInString{7}}}}1
{8}{{{\ColorIfNotInString{8}}}}1
{9}{{{\ColorIfNotInString{9}}}}1
}
\begin{document}
\lstset{language=C++ , keywordstyle=\color{blue}\bfseries ,commentstyle=\color{white}, stringstyle=\ttfamily, showstringspaces=false}
\begin{lstlisting}[basicstyle=\ttfamily]
#include<iostream>
using namespace std ;
for (col = 1 ; col<= 5 ; col++)
cout << "Enter your number : " ;
cin >> a[row][col] ;
\end{lstlisting}
\end{document}
This is the output which I get:
Where I want "Enter your number " in reddish-brown.
So what should I do for that?
Best Answer
The following code produces the result I think you want:
I removed everything not necessary, and modified the
\lstset
to includestringstyle=\ttfamily\color{red!50!brown}
. The star before the first argument of the literate programming\lstset
protects numerals in environments such as comments and strings.Playing around a bit gets you much more horizontally compact code, which may be clearer to read. I've put additions in the square brackets here, but they can also go in
\lstset