简体   繁体   中英

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.

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 .

#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.

The function GetAsyncKeyState() does exactly what you ask for. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM