Align code in lstlisting

horizontal alignmentlistings

I'm trying to learn the TeX file given by my teacher. I managed to link the C++ file to the listing using:

\lstset{language=C++,
    % numbers=left,
    %   stepnumber=1,
    numberstyle=\ttfamily,
    basicstyle=\ttfamily,
    keywordstyle=\color{blue}\ttfamily,
    stringstyle=\color{red}\ttfamily,
    commentstyle=\color{gray}\ttfamily,
    morecomment=[l][\color{magenta}]{\#}
}
\lstinputlisting[label={code},caption={\textit{Source code} program}, language={C}]{main.cpp}

and i got:

this

I try to use lstlisting to explain the code separately. I use:

\begin{lstlisting}[label={code},caption={isiArray Function}, language={C}]
        
        void isiArray(int arr[],int *arrLength){
            int i;
            for(i=0;i<*arrLength;i++){
                cin>>arr[i];
            }
        }
    
    \end{lstlisting}

But i got:

this

The code is not aligned on the left as in the previous code. Why is this happening? How to set the alignment to left?

Best Answer

Since listings are virtually set verbatim, it considers spaces as well, so your indentation of the entire code block within the lstlisting environment is reflected as part of the output. Remove the indentation or use the gobble argument to remove an initial set of spaces.

enter image description here

\documentclass{article}

\usepackage{listings,lipsum}

\begin{document}

\sloppy\lipsum[1]

\begin{lstlisting}[caption={isiArray Function 1}, language={C}, basicstyle=\ttfamily]
        void isiArray(int arr[],int *arrLength){
          int i;
          for(i=0;i<*arrLength;i++){
            cin>>arr[i];
          }
        }
\end{lstlisting}

\begin{lstlisting}[gobble=8, caption={isiArray Function 2}, language={C}, basicstyle=\ttfamily]
        void isiArray(int arr[],int *arrLength){
          int i;
          for(i=0;i<*arrLength;i++){
            cin>>arr[i];
          }
        }
\end{lstlisting}

\begin{lstlisting}[caption={isiArray Function 3}, language={C}, basicstyle=\ttfamily]
void isiArray(int arr[],int *arrLength){
  int i;
  for(i=0;i<*arrLength;i++){
    cin>>arr[i];
  }
}
\end{lstlisting}

\end{document}