簡體   English   中英

C-一次從標准輸入大字串讀取一個字符

[英]C - Reading one character at a time from stdin in a large string

我想一次從標准輸入中讀取一個字符並對其進行操作。 例如輸入

abcdefghijklmnopqrstuvwxyz

我想要的是,一旦輸入a (第一個字符)就對其進行操作(對a的操作應在用戶輸入b之前進行),然后對b進行操作,依此類推。

也許這是其他解決方案。

取自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;
}

我想你想要這樣的東西。

#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;
}

由於您未指定操作系統,因此我將給出適合Windows操作系統的建議。

函數GetAsyncKeyState()完全滿足您的要求。 您可以從此鏈接閱讀其文檔。

作為其用法的快速示例:

#include <Windows.h>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM