简体   繁体   English

C-一次从标准输入大字串读取一个字符

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

I want to read one character at a time from standard input and operate on that. 我想一次从标准输入中读取一个字符并对其进行操作。 For example, input 例如输入

abcdefghijklmnopqrstuvwxyz

What I want is, to operate on a (which is the first character) as soon as it has been entered (the operation on a should be done before the user enters b ) and then operate on b and so on. 我想要的是,一旦输入a (第一个字符)就对其进行操作(对a的操作应在用户输入b之前进行),然后对b进行操作,依此类推。

Maybe this other solution. 也许这是其他解决方案。

Taken from https://www.gnu.org/software/libc/manual/html_node/Noncanon-Example.html and https://ftp.gnu.org/old-gnu/Manuals/glibc-2.2.3/html_chapter/libc_17.html . 取自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;
}

I think you want something like this. 我想你想要这样的东西。

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

Since you did not specify an operating system, I am going to give a suggestion suitable for the windows operating system. 由于您未指定操作系统,因此我将给出适合Windows操作系统的建议。

The function GetAsyncKeyState() does exactly what you ask for. 函数GetAsyncKeyState()完全满足您的要求。 You can read its documentation from this link . 您可以从此链接阅读其文档。

As a quick example on its usage: 作为其用法的快速示例:

#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