1

I have a question about showing C++ code in LateX

When I do the following, the C++ goes past the page. Is there a way to fix this?

\documentclass{article} 

\newcommand{\dd}[1]{\mathrm{d}#1}
\usepackage[parfill]{parskip}
\usepackage{listings}
\usepackage{xcolor} % for setting colors
\usepackage{breqn}

% set the default code style
\lstset{
    frame=tb, % draw a frame at the top and bottom of the code block
    tabsize=4, % tab space width
    showstringspaces=false, % don't mark spaces in strings
    numbers=left, % display line numbers on the left
    commentstyle=\color{green}, % comment color
    keywordstyle=\color{blue}, % keyword color
    stringstyle=\color{red} % string color
}

\begin{document}

\section{$\Delta A_2$ Derivation: Comparison with CRIS2}


First, let us start by showing the C++ code:
\begin{lstlisting}[language=C++, caption={C++ code using listings}]
{
  else if (evaltype == 5) 
  {
    for (std::size_t i=startp;i<p.size();++i) 
    {
      double & x = p[i].first; //input
      double & y = p[i].second; //result
      double q1 = rtx[8]-(cafdf(rtx[0],rtx[4]*x*x*x)-rtx[3])/rtx[1];
      double xi = crsxib(q1); 
      double p1i = 23.0/(1.0-xi)+ab[5]+xi*(11.0*ab[2]+xi*(2.0*ab[3]+xi*33.0*ab[4]));
      p1i *= 4.3723240245*ab[0];
      double si = (1.0+ci*(ab[99]+xi*(ab[44]+xi*ab[33])))/(3.0*(1.0-xi));
      y = p1i*xi*xy/abc[2]/dde[2]*(x/(1.0+dd*(x-1.0)))*(q/(1.0+si*(x-1.0)))*(x/(1.0+ci*(x-1.0)));
    }
  }
}
\end{lstlisting}
1

Please in your \lstset add breaklines = true, then with

\documentclass{article} 

\newcommand{\dd}[1]{\mathrm{d}#1}
\usepackage[parfill]{parskip}
\usepackage{listings}
\usepackage{xcolor} % for setting colors
\usepackage{breqn}

% set the default code style
\lstset{
frame=tlb, % draw a frame at the top and bottom of the code block
tabsize=4, % tab space width
showstringspaces=false, % don't mark spaces in strings
numbers=left, % display line numbers on the left
commentstyle=\color{green}, % comment color
keywordstyle=\color{blue}, % keyword color
stringstyle=\color{red}, % string color
breaklines = true,
}

\begin{document}

\begin{lstlisting}[language=C++, caption={C++ code using listings}]
{
  else if (evaltype == 5) 
  {
    for (std::size_t i=startp;i<p.size();++i) 
    {
      double & x = p[i].first; //input
      double & y = p[i].second; //result
      double q1 = rtx[8]-(cafdf(rtx[0],rtx[4]*x*x*x)-rtx[3])/rtx[1];
      double xi = crsxib(q1); 
      double p1i = 23.0/(1.0-xi)+ab[5]+xi*(11.0*ab[2]+xi*(2.0*ab[3]+xi*33.0*ab[4]));
      p1i *= 4.3723240245*ab[0];
      double si = (1.0+ci*(ab[99]+xi*(ab[44]+xi*ab[33])))/(3.0*(1.0-xi));
      y = p1i*xi*xy/abc[2]/dde[2]*(x/(1.0+dd*(x-1.0)))*(q/(1.0+si*(x-1.0)))*(x/(1.0+ci*(x-1.0)));
    }
  }
}
\end{lstlisting}

\end{document}

You will see

cpp lstlisting

Not the answer you're looking for? Browse other questions tagged or ask your own question.