Search code examples
c++stringncursescout

The newline starts where the previus line ends in my hackertyper program


I am working on this that shows a character when a key is pressed, like on the hackertyper website. But when another line is shown, it aligns it at the end of the previus line.

Here's how the lines should show:

Hello,          World!
This is a multi-line string.

Here's how they're shown:

Hello,          World!
                      This is a multi-line string

And here's the code:

#include <iostream>
#include <thread>
#include <chrono>
#include <ncurses.h>
using namespace std;

int main() {
    string text = "Hello,          World!\nThis is a multi-line string.";
    // Initialize ncurses
    initscr();
    // Enables immediate input mode for capturing key presses in real-time.
    cbreak();
    // Disables showing your input characters, so it won't be gibberish
    noecho();

    for (char c : text) {
        if (c == ' ') {
            cout << c << flush;
        }
        else {
            getch();
            cout << c << flush;
        }
    }

    endwin();
    return 0;
}

Solution

  • I fixed the issue by adding another if statement inside the else statement like this:

    getch();
    if (c == '\n') {
        cout << '\r';
    }
    cout << c << flush;