【问题标题】:How can I limit the length of input that user can enter in the console?如何限制用户可以在控制台中输入的输入长度?
【发布时间】:2021-09-21 05:20:57
【问题描述】:

我正在开发一个程序,它在程序运行时在文本周围显示一个框架 我想通过控制台限制这个输入,因为如果用户输入很长的输入,他会越过框架并转到下一行等等,破坏框架的整个设计。框架在程序中运行良好,但在这种情况下,它变得非常糟糕。

我使用下面的代码来获取输入

char entered_name[15];
print(">");      
scanf("%s",entered_name);

【问题讨论】:

  • 为此,我认为您必须编写自己的get_line 函数,该函数将重复调用getchar 并跟踪输入的字符数。当到达框的右端时,将丢弃更多字符,并且可能会发出哔声,或类似的声音。
  • @JohnKugelman 我只是使用通常的 scanf();并将输入存储在 char 字符串中
  • @SGeorgiades 我已经尝试过getchar(),但我也看到输入越过框架,它只是让我得到输入的第一个字符,但显示用户在输入时输入的内容。
  • 这取决于操作系统。告诉我们您正在使用什么操作系统、编译器等。
  • Engineer-A,不能使用标准 C 和库。

标签: c windows console-application


【解决方案1】:

据我所见,我猜你是在 Windows (MS - DOS) 环境下,如果是这种情况,你可以使用conio.h 中的_getch() 函数。并创建一个自定义函数来获取输入。应该是这样的,

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>

#define MAX 15

char *getInput(void)
{
    int c = 0;
    size_t i = 0;
    char *buff = NULL;

    buff = calloc(0, MAX); /* you don't need to NULL terminate */

    if (buff == NULL)
    {
        /* handle oom */
    }

    while ((c = _getch()) != EOF && i < 15 && c != '\r') /* note \r insted of \n since we are on MS-DOS */
    {
        if (isalpha(c)) /* since you are asking for last name, check if its a letter */
        {
            putchar(c);
            buff[i++] = (char)c;
        }
    }

    return buff; /* don't forget to free */
}

【讨论】:

  • "猜测您在 Windows (MS - DOS) 环境中'--> 一个合理的猜测。希望您是正确的,如果 OP 声明操作系统会更好。
【解决方案2】:

大概是这样的:

char *get_line(int maxline)
{
    bool done = FALSE;
    char *buffer = calloc(maxline + 1,sizeof(char));
    char chr;
    int idx = 0;

    while (!done) {
        if ((chr = getchar()) == EOF)
            done = TRUE;
        else if (isgraph(chr)) {
            if (idx < maxline)
                buffer[idx++] = chr;
            else printf("\b \b\a");
        } else if (chr == 8) {
            if (idx > 0) {
                printf(" \b");
                buffer[--idx] = 0;
            }
        } else if (chr == 10  ||  chr == 13) {
            putchar(chr == 13 ? 10 : 13);
            done = TRUE;
        }
    }
    buffer[idx] = 0;
    return buffer;
}

其中参数maxline是输入的长度限制,应该是窗口的宽度,减去提示的长度,在行尾加一个空格。

【讨论】:

  • char chr; ... (chr = getchar()) == EOFchar 未签名时永远不会为真。
猜你喜欢
  • 2012-02-29
  • 2013-12-04
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
相关资源
最近更新 更多