在我的 Latex 文件中包含 C++ 程式碼

在我的 Latex 文件中包含 C++ 程式碼

我試圖在我的乳膠文檔中包含 C++ 程式碼。但是,我所嘗試的方法不起作用。其他一切都工作正常,但我沒有看到 C++ 顯示為 C++ 程式碼。它只是以與“Alpha 粒子..”文本相同的格式編寫

這是 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

您想要為清單使用不同的字體系列。由於關鍵字在樣式中為粗體,因此標準電腦現代打字機字體不太適合,因為它們沒有粗體。

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

這裡我展示listingsverbatimbox進行比較。透過使用該verbnobox環境,可以在清單中間獲得分頁符號。

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

在此輸入影像描述

相關內容