LaTeX实战经验:如何插入程序代码

>> 点击此处查看 【 LaTeX实战经验:新手须知 】

插入程序代码

传统一点, \usepackage{listings}, 详情可以使用texdoc listings查看。

\lstset{language=C}
\begin{lstlisting}
#include <iostream>
using namespace std;

int main()
{
    cout<<"hello"<<endl;
    return 0;
}
\end{lstlisting}

对效果进行一些定制:

\usepackage{listings}
\usepackage{xcolor}
\lstset{
    numbers=left, 
    numberstyle= \tiny, 
    keywordstyle= \color{ blue!70},
    commentstyle= \color{red!50!green!50!blue!50}, 
    frame=shadowbox, % 阴影效果
    rulesepcolor= \color{ red!20!green!20!blue!20} ,
    escapeinside=``, % 英文分号中可写入中文
    xleftmargin=2em,xrightmargin=2em, aboveskip=1em,
    framexleftmargin=2em
} 

效果:

这里写图片描述

mac 定制代码字体
%!TEX program = xelatex
\documentclass{article}
\usepackage{listings}
\usepackage{fontspec} % 定制字体
\newfontfamily\menlo{Menlo}
\usepackage{xcolor} % 定制颜色
\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}
\lstset{ %
backgroundcolor=\color{white},      % choose the background color
basicstyle=\footnotesize\ttfamily,  % size of fonts used for the code
columns=fullflexible,
tabsize=4,
breaklines=true,               % automatic line breaking only at whitespace
captionpos=b,                  % sets the caption-position to bottom
commentstyle=\color{mygreen},  % comment style
escapeinside={\%*}{*)},        % if you want to add LaTeX within your code
keywordstyle=\color{blue},     % keyword style
stringstyle=\color{mymauve}\ttfamily,  % string literal style
frame=single,
rulesepcolor=\color{red!20!green!20!blue!20},
% identifierstyle=\color{red},
language=c++,
}
\begin{document}
\begin{lstlisting}[language={[ANSI]C},
        numbers=left,
        numberstyle=\tiny\menlo,
        basicstyle=\small\menlo]
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>

#define SIZE 26

int
main (int argc, char *argv[])
{
  int array[SIZE];
  int i;
  char c;

  for (i = 0; i < SIZE; i++)
    array[i] = 0;

  while ((c = getchar ()) != EOF)
    {
      if (isupper (c))
        {
          array[c - 'A']++;
        }
    }
  for (i = 0; i < 26; i++)
    printf ("%c:%5d\n", (char) ('A' + i), array[i]);

  return 0;
}
\end{lstlisting}
\end{document}
% Local Variables:
% TeX-engine: xetex
% End:

效果图:
这里写图片描述

参考:https://www.zhihu.com/question/30957600

  • 27
    点赞
  • 135
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值