5

I currently have a problem with writing C++ in latex. I have a very long string of text inside my code, that interferes with the space.

enter image description here

So how do I fix this??

The code:

\documentclass[11pt,a4paper,oneside]{article}
\usepackage[utf8]{inputenc}

\usepackage{listings}
\usepackage{xcolor}
\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{lstlisting}[language=C++]
while(again == 1)
    { //again er defineret som 1, loekken koeres igen.
    cout << "Velkommen til BMI beregneren!" << endl;
    cout << "\nEr du en mand eller kvinde? Tast 1 for mand, tast 2 for kvinde" << endl;
    cin >> sex;
    cout << "Indtast din hojde i cm." << endl;
    cin >> height;
    cout << "Indtast din vaegt i KG." << endl;
    cin >> weight;
\end{lstlisting}
2
  • 2
    Use listings' breaklines option.
    – jub0bs
    May 10 '15 at 21:01
  • It doesn't seem to work. How do I use the "breakline" option?
    – RandomDude
    May 10 '15 at 21:03
8

The breaklines option, pointed out by Jubobs, works indeed and without any warnings. Here is how you can do it:

\documentclass[11pt,a4paper,oneside]{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\usepackage{xcolor}
\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}
\begin{lstlisting}[language=C++,breaklines]
while(again == 1)
    { //again er defineret som 1, loekken koeres igen.
    cout << "Velkommen til BMI beregneren!" << endl;
    cout << "\nEr du en mand eller kvinde? Tast 1 for mand, tast 2 for kvinde" << endl;
    cin >> sex;
    cout << "Indtast din hojde i cm." << endl;
    cin >> height;
    cout << "Indtast din vaegt i KG." << endl;
    cin >> weight;
\end{lstlisting}
\end{document}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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