c++turbo-pascalreadkey

C++ read user input without pressing return (Mac OS X), same as readkey in Turbo Pascal


I have seen many posts about this, but none of them answer the question, they give examples that do not work, all you get is more error messages, or just sent off at other tangents. ncurses is continually mentioned yet none of the examples I have found work on OS X, despite the claims. Either the examples are wrong or they are not actually tested before posting. I would add a comment to these posts, but as I am a new user I am not allowed to ask anything about them, which is also ridiculous as that would be far easier than having to start a new topic.

I want the program to ask a question, wait for user input and read each key pressed without the return key being pressed, I was some years ago fairly proficient in Turbo Pascal, and this was so easy to do like most things in Pascal, it would just work... I thought C++ would be similar, instead you are just continually faced with contrary platform specific use cases, and examples that never compile.

I am using CLion 2017.2.2 on OS X.


Solution

  • Here is an example code for ncurses. I tested it under linux but it should also work under mac os.

    #include <stdlib.h>
    #include <stdio.h>
    #include <curses.h>
    
    
    int main(void) {
        WINDOW * mainwin;
    
        if ( (mainwin = initscr()) == NULL ) {
              fprintf(stderr, "Error initialising ncurses.\n");
              exit(EXIT_FAILURE);
        }
    
        mvaddstr(13, 33, "Input: ");
        refresh();
        char input[2];
        input[0] = getch();
        input[1] = '\0';
        mvaddstr(15, 33, "Your Input is: ");
        mvaddstr(15, 48, input);
        mvaddstr(17, 33, "Press any key to exit");
        getch();
    
        delwin(mainwin);
        endwin();
        refresh();
    
        return EXIT_SUCCESS;
    }
    

    It's necessary to link against ncurses. I use cmake to manage my build:

    cmake_minimum_required(VERSION 3.5)
    project(ncurses)
    set(CMAKE_CXX_STANDARD 11)
    
    set(CMAKE_BUILD_TYPE Debug)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Wextra")
    
    find_package(Curses REQUIRED)
    
    add_executable(ncurses main.cpp)
    target_link_libraries(ncurses ${CURSES_LIBRARIES})