简体   繁体   English

C ++读取用户输入而无需按回车键(Mac OS X),与Turbo Pascal中的readkey相同

[英]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. 不断提到ncurses,尽管有这些主张,但我找不到在OS X上可用的示例。 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. 我想让程序问一个问题,等待用户输入并在不按下回车键的情况下读取每个按键,我几年前相当精通Turbo Pascal,这很容易做到,就像Pascal中的大多数事情一样,可以正常工作...我以为C ++会类似,相反,您只是不断面对特定于平台的相反用例,以及从未编译过的示例。

I am using CLion 2017.2.2 on OS X. 我在OS X上使用CLion 2017.2.2。

Here is an example code for ncurses. 这是ncurses的示例代码。 I tested it under linux but it should also work under mac os. 我在linux下测试了它,但它也可以在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. 有必要对ncurses进行链接。 I use cmake to manage my build: 我使用cmake来管理我的构建:

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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM