How to insert code with accents with listings?

You can load the package listingsutf8 and then set the encoding using \lstset{inputencoding=utf8/latin1}:

\documentclass{article}

\usepackage{listingsutf8}
\usepackage[spanish]{babel}

\begin{document}

\lstset{inputencoding=utf8/latin1}
\lstinputlisting[language=C++]{code.cpp}

\end{document}

The accepted solution didn't work for me, so here is mine:

\usepackage{listings} % ordinary listings package

and then configure letter mappings - these mappings are for the Czech languaguge but you can configure your own

\lstset{
     literate=%
         {á}{{\'a}}1
         {í}{{\'i}}1
         {é}{{\'e}}1
         {ý}{{\'y}}1
         {ú}{{\'u}}1
         {ó}{{\'o}}1
         {ě}{{\v{e}}}1
         {š}{{\v{s}}}1
         {č}{{\v{c}}}1
         {ř}{{\v{r}}}1
         {ž}{{\v{z}}}1
         {ď}{{\v{d}}}1
         {ť}{{\v{t}}}1
         {ň}{{\v{n}}}1                
         {ů}{{\r{u}}}1
         {Á}{{\'A}}1
         {Í}{{\'I}}1
         {É}{{\'E}}1
         {Ý}{{\'Y}}1
         {Ú}{{\'U}}1
         {Ó}{{\'O}}1
         {Ě}{{\v{E}}}1
         {Š}{{\v{S}}}1
         {Č}{{\v{C}}}1
         {Ř}{{\v{R}}}1
         {Ž}{{\v{Z}}}1
         {Ď}{{\v{D}}}1
         {Ť}{{\v{T}}}1
         {Ň}{{\v{N}}}1                
         {Ů}{{\r{U}}}1    
}

None of the above worked here, just this way:

\usepackage[T1]{fontenc}            
\usepackage[brazil]{babel}
\usepackage[utf8]{inputenc} 

\usepackage{listings}

\lstset{
    language=bash,   %% PHP, C, Java, etc... bash is the standard
    extendedchars=true,
    inputencoding=latin1
}