2

How to write a c++ code in LaTeX with proper alignment?

I am providing more details about my question below: I need to write this:

if(a==b):
    a=2
    b=2

I need to write this above code in exactly the same way I put it above. But if I use the following code in LaTeX:

\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{makeidx}
\usepackage{graphicx}
\begin{document}
if(a==b):
    a=2
    b=2

\end{document}

I am not getting my required output. Can someone please help me out on how to get the desired output with proper alignment?

FHZ
  • 3,939
Charlotte
  • 963

2 Answers2

2

The package listings enables users to create many customized styles to insert code in TeX. Users can also insert code from external files or set any desired color scheme, for example this and this.

A MWE follows:

\documentclass[12pt,a4paper]{article}
\usepackage{listings}

\begin{document} \begin{lstlisting} if(a==b): a=2 b=2 \end{lstlisting}

\begin{lstlisting}[language=C] if(a==b): a=2 b=2 \end{lstlisting}

\end{document}

Notice the ifis with bold when language=C is used.

enter image description here

FHZ
  • 3,939
1

Using the following:

\begin{verbatim}
if(a==b):
    a=2
    b=2
\end{verbatim}

Should give you the desired result.

EDIT

This is the result:

enter image description here

Verbatim is used to write code as is, ignoring commands etc. Have a look at this or this for further info.

eliasf
  • 141