# Block text alignment not correct with monospaced font

I want to define \code such that it would use some monospace font, to display code.

Initially I used \texttt but I had some problems with the error:

!pdfTeX error: /Users/az/.local/bin/pdflatex (file cmttb10): Font cmttb10 at 720 not found


The answer here suggested to \fontencoding{T1}\fontfamily{lmtt}\selectfont. It seems to also work without \fontencoding{T1}, so I left that away. (But maybe that's wrong? What does it do?)

In the small example below, this error also only occurs with \usepackage{bold-extra}. If I leave that away, all three variants seem to work (in this example). Not sure which is better. The font looks slightly different in all 3 cases.

However, this is not really the question here (although I'm also curious about that).

In all 3 variants, the problem is that it doesn't properly aligns the block text. Why? How can I fix that?

%!TEX encoding = UTF-8 Unicode
% some playground, to test problems, reproduce minimal example
\documentclass[paper=a4, fontsize=11pt]{scrbook}
\usepackage[utf8]{inputenc}
\usepackage{lipsum}
\usepackage{bold-extra}

% https://tex.stackexchange.com/questions/87891/typewriter-text-in-sections-with-acm-sig-alternate-document-class
%\newcommand{\code}[1]{\texttt{#1}}
%\newcommand{\code}[1]{{\fontencoding{T1}\fontfamily{lmtt}\selectfont#1}}
\newcommand{\code}[1]{{\fontfamily{lmtt}\selectfont#1}}

\begin{document}
\tableofcontents

\chapter{Chapter with \code{code}}
\section{Section with \code{code}}

Code:
\code{hello\_world}, \code{hello\_world}, \code{hello\_world}, \code{hello\_world}, \code{hello\_world}, \code{hello\_world}, \code{hello\_world}, \code{hello\_world}, \code{hello\_world}.

\lipsum[0-1]
\end{document}


It looks like this:

The question here is somewhat related. However, there the whole text uses the monospace font, and the author doesn't want the monospaced spaces to be mono-spaced. However, in my question, the spaces are not monospaced, so this should not be the problem here.

\setlength\emergencystretch{\hsize}\hbadness=10000

Via, where it is also explained that this is better than just using \sloppy.