【问题标题】:C - Reading one character at a time from stdin in a large stringC - 从大字符串中的标准输入一次读取一个字符
【发布时间】:2023-03-11 04:04:01
【问题描述】:

我想从标准输入一次读取一个字符并对其进行操作。比如输入

abcdefghijklmnopqrstuvwxyz

我想要的是,在输入a(这是第一个字符)后立即对其进行操作(对a的操作应该在用户输入b之前完成)然后再操作b 等等。

【问题讨论】:

标签: c input formatting


【解决方案1】:

也许这是其他解决方案。

取自https://www.gnu.org/software/libc/manual/html_node/Noncanon-Example.htmlhttps://ftp.gnu.org/old-gnu/Manuals/glibc-2.2.3/html_chapter/libc_17.html

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>

/* Use this variable to remember original terminal attributes. */

struct termios saved_attributes;

void
reset_input_mode (void)
{
  tcsetattr (STDIN_FILENO, TCSANOW, &saved_attributes);
}

void
set_input_mode (void)
{
  struct termios tattr;
  char *name;

  /* Make sure stdin is a terminal. */
  if (!isatty (STDIN_FILENO))
    {
      fprintf (stderr, "Not a terminal.\n");
      exit (EXIT_FAILURE);
    }

  /* Save the terminal attributes so we can restore them later. */
  tcgetattr (STDIN_FILENO, &saved_attributes);
  atexit (reset_input_mode);

  /* Set the funny terminal modes. */
  tcgetattr (STDIN_FILENO, &tattr);
  tattr.c_lflag &= ~(ICANON|ECHO); /* Clear ICANON and ECHO. */
  tattr.c_cc[VMIN] = 1;
  tattr.c_cc[VTIME] = 0;
  tcsetattr (STDIN_FILENO, TCSAFLUSH, &tattr);
}


int
main (void)
{
  char c;

  set_input_mode ();

  while (1)
    {
      read (STDIN_FILENO, &c, 1);
      if (c == '\004')          /* C-d */
        break;
      else
        putchar (c);
    }

  return EXIT_SUCCESS;
}

【讨论】:

  • 这可能是一个答案,但我们不知道他的操作系统,另外,您应该将 保存终端属性以便我们稍后恢复它们部分放在main (一开始)而不是每次按下键时调用它。
【解决方案2】:

我想你想要这样的东西。

#include <stdio.h>

int main ()
{
  int c;
  puts ("Enter text");
  do {
    c = getchar();
    putchar (c); //do whatever you want with this character.
  } while (c != '\0');

  return 0;
}

【讨论】:

  • 您的回答是正确的,但我怀疑 OP 想在按 Enter 之前查看这些更改。
  • 是的。我想在按回车之前对输入进行操作。该操作应在输入字符后立即开始。
  • @bigcoder,Luis Daniel 的代码正是这样做的,但是在您按下 Enter 之前,这些更改是不可见的,因为您的终端在规范模式下工作,getch(非标准)是您正在寻找的.
【解决方案3】:

由于您没有指定操作系统,我将给出一个适合windows操作系统的建议。

函数GetAsyncKeyState() 完全符合您的要求。您可以从this link 阅读其文档。

作为其用法的简单示例:

#include <Windows.h>

int main(void)
{
    while(1) {
        if(GetAsyncKeyState('A') & 0x8000) {
            /* code goes here */
            break;
        }
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多