[英]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.html和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;
}
我想你想要这样的东西。
#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.