LaTeX文書にC++コードを含める

LaTeX文書にC++コードを含める

私は C++ コードを LaTeX ドキュメントに組み込もうとしています。しかし、私が試したことはうまくいきません。他のすべてはうまくいきますが、C++ が C++ コードとして表示されません。それは単に「アルファ粒子 ..」テキストと同じ形式で書かれています。

MWE は次のとおりです: tex は次のとおりです:

\documentclass{article}  
 \usepackage{listings}
\usepackage{xcolor}
\lstset { 
language=C++,
backgroundcolor=\color{black!5}, % set backgroundcolor
basicstyle=\footnotesize,% basic font setting
}

\begin{document}  
Alpha particles \cite{wikip} (named \cite{Comp} after and denoted by the first letter     in the
Greek alphabet,\[\alpha\]) consist of two protons and two neutrons bound
together.
This means that an particle is a helium nucleus. 

\begin{lstlisting}
int size =1;
*ptr = Mole:getMole(size + 1);
\end{lstlisting}

\bibliographystyle{plain}
\bibliography{BibName}

\end{document}

期待される結果:

ここに画像の説明を入力してください

答え1

リストには別のフォント ファミリを使用します。キーワードは太字のスタイルなので、標準の Computer Modern Typewriter フォントは太字ではないため適していません。

中幅シリーズと太字をうまく区別できる優れた等幅フォント ファミリは BeraMono です。

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{listings}
\usepackage{xcolor}
\usepackage[scaled=.85]{beramono}

\lstset{
  language=C++,
  backgroundcolor=\color{black!5}, % set backgroundcolor
  basicstyle=\footnotesize\ttfamily,% basic font setting
  columns=fullflexible,
}

\begin{document}

Alpha particles (named after and denoted by the first letter in the Greek alphabet,
$\alpha$) consist of two protons and two neutrons bound together. This means that an
particle is a helium nucleus.

\begin{lstlisting}
int size =1;
*ptr = Mole:getMole(size + 1);
\end{lstlisting}

\end{document}

インライン数式の場合は、数式を中央に配置するではなく、$\alpha$または を使用することに注意してください。\(\alpha\)\[\alpha\]

このトピックに関係のない引用を削除しました。

ここに画像の説明を入力してください

答え2

動作しない場合は、キーワードの強調表示が必要ない場合はパッケージlistingsがあります。verbatimbox

ここで比較のためにlistingsとを示します。環境を使用すると、リストの途中でページ区切りを取得できます。verbatimboxverbnobox

\documentclass{article}
\usepackage{xcolor}
% LISTINGS PREP
\usepackage{listings}
\lstset { 
language=C++,
backgroundcolor=\color{black!5}, % set backgroundcolor
basicstyle=\footnotesize,% basic font setting
}
% VERBATIMBOX PREP
\usepackage{verbatimbox}
\def\codesize{\footnotesize}
\newsavebox\thecolorfield
\newcommand\setcolorfield[1][blue!9!gray!8]{%
  \savebox{\thecolorfield}{\codesize%
    \makebox[0pt][l]{\textcolor{#1}{%
    \rule[-\dp\strutbox]{\textwidth}{\dimexpr\ht\strutbox+\dp\strutbox}}}}%
}
\def\colorfield{\usebox{\thecolorfield}}
\setcolorfield
%
\begin{document}  
WITH LISTINGS:
\begin{lstlisting}
int size =1;
*ptr = Mole:getMole(size + 1);
\end{lstlisting}

WITH VERBATIMBOX (ttfamily):
\begin{verbnobox}[\colorfield\ttfamily\codesize]
int size =1;
*ptr = Mole:getMole(size + 1);
\end{verbnobox}

\setcolorfield[green!8]
WITH VERBATIMBOX (bold-rmfamily):
\begin{verbnobox}[\colorfield\rmfamily\bfseries\codesize]
int size =1;
*ptr = Mole:getMole(size + 1);
\end{verbnobox}
\end{document}

ここに画像の説明を入力してください

関連情報