![在我的乳胶文档中包含 C++ 代码](https://linux22.com/image/476925/%E5%9C%A8%E6%88%91%E7%9A%84%E4%B9%B3%E8%83%B6%E6%96%87%E6%A1%A3%E4%B8%AD%E5%8C%85%E5%90%AB%20C%2B%2B%20%E4%BB%A3%E7%A0%81.png)
我正在尝试将 C++ 代码包含到我的 latex 文档中。但是,我尝试的方法不起作用。其他一切都正常,但我没有看到 C++ 显示为 C++ 代码。它只是以与“Alpha 粒子 ..”文本相同的格式编写
这是 MWE:文本是:
\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
和verbatimbox
以作比较。通过使用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}