Search code examples
c++newlinencurses

'\n' Prints extra space in ncurses C++


I am trying to write a basic app in C++ using ncurses library. All I wanted was to print out characters that user presses manually. Here's the code:

#include <iostream>
#include <curses.h>

int main(int argc, char* argv[]) {
  initscr();            // Initialize the curses library
  timeout(0);           // Set getch() to be non-blocking
  keypad(stdscr, TRUE); // Enable special keys
  noecho();             // Disable automatic echoing of characters

  bool continue_ = true;
  
  while (continue_) {
    int c = getch();

    if (c != ERR) {
      switch (c) {
        case 27:
          continue_ = false;
          break;
        case KEY_ENTER:
        case '\r':
          std::cout << '\n'; // prints extra space
          break;
        default:
          std::cout << (char)c;
          break;
      } 
      std::cout.flush(); // without this, characters only appear after pressing enter
    }
  }
  
  endwin(); // End curses mode
  return 0;
}

The problem is that when I press enter key, it prints the newline character ('\n'), but with extra spaces. Here's sample output:

Some text
         After Enter:
                     I am going forward
                                       why?

Note: I realized that extra space count is equal to keys I pressed (not including enter).


Solution

  • You can use printw instead:

        ...
        case '\r':
          printw("\n");
          break;
        default:
          printw("%c",c);
          break;
       ...