3

I hope the question isn't to ambiguous.

when I ask:

int main()
{

string name = {""};

cout << "Please enter a name: " << endl;
getline(cin, name);
//user enters 12 characters stop displaying next literal keypresses.
enter code here
}

I would like to be able to limit the amount of times the user can enter a char on screen. Example, the screen stops displaying characters after length 12?

If so what would be the library and command line for doing something like this?

Wanting to this as, I have a ascii art drawn on the CMD, and when I cout the statement at x,y anything over 12 characters long inputed draws over the ascii art.

I hope this makes sense :'{ Thank you!

4

3 回答 3

9

默认情况下,控制台处于熟模式(规范模式、行模式……)。这表示

  1. 控制台驱动程序在将数据传递给您的应用程序之前正在缓冲数据
  2. 字符将由控制台驱动程序自动回显到控制台

通常,这意味着您的程序只在一行结束后才获取输入,即当按下回车时。由于自动回声,这些角色已经出现在屏幕上。

这两个设置都可以独立更改,但是机制是 -- 不幸的是 -- 一个特定于操作系统的调用:

对于窗口它是SetConsoleMode()

HANDLE h_stdin = GetStdHandle(STD_INPUT_HANDLE); 
DWORD mode = 0;

// get chars immediately
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & ~ENABLE_LINE_INPUT));


// display input echo, set after 12th char.
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & ~ENABLE_ECHO_INPUT));

正如您自己所指出的,Windows 仍然提供conio.h包括非回显_getch()(现在带有下划线)。您始终可以使用它并手动回显字符。_getch()简单地将控制台线路模式开/关,回声开/关开关包装成一个功能。

编辑:这里有一个关于使用的例子_getch()。我有点忙于正确完成它,我避免发布可能有错误的代码。

在 *nix 下,您很可能想要使用 curses/termcap/terminfo。如果您想要更精简的方法,低级例程记录在termios/tty_ioctl 中

#include <sys/types.h>
#include <termios.h>

struct termios tcattr;

// enable non-canonical mode, get raw chars as they are generated
tcgetattr(STDIN_FILENO, &tcattr);
tcattr.c_lflag &= ~ICANON;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &tcattr);

// disable echo
tcgetattr(STDIN_FILENO, &tcattr);
tcattr.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &tcattr);
于 2015-09-01T07:49:10.737 回答
0

您可以使用scanf("%c",&character)从 1 到 12 的循环并将它们附加到预分配的缓冲区。

于 2015-09-01T07:38:26.073 回答
0

正如我在评论中提到的,我提到了一种使用 _getch(); 发现的方法;并手动显示每个字符。

简化版:

#include <iostream>
#include <string>
#include <conio.h>

using namespace std;
string name = "";


int main() 
{
    char temp;
    cout << "Enter a string: ";
    for (int i = 0; i < 12; i++) { //Replace 12 with character limit you want
        temp = _getch();
        name += temp;
        cout << temp;
    }
    system("PAUSE");
}

这使您可以将每个按键都按其按下,同时将每个按下的字符连接到一个名为 name 的字符串。

然后稍后在您使用它的任何程序中,您可以将全名显示为单个字符串类型。

于 2015-09-03T06:56:18.117 回答