问题描述
我试图做一个简单的命令暂停用户输入。我认为它会在的bash脚本是有用的。
I'm trying to make a simple command that pauses for user input. I think it'll be useful in Bash scripts.
下面是我的code:
#include <stdio.h>
int main() {
char key[1];
puts("Press any key to continue...");
fgets(key,1,stdin);
}
它甚至没有暂停用户输入。
It doesn't even pause for user input.
我之前试过用残培()(ncurses的)。事情的经过后,屏幕一片空白,当我pressed一个键,就回什么最初是在屏幕上,我看到:
I tried earlier to use getch() (ncurses). What happened is, the screen went blank and when I pressed a key, it went back to what was originally on the screen, and I saw:
$ ./pause
Press any key to continue...
$
这有点是我想要的。但是,所有我想要的是暂停相当于
在DOS / Windows命令(我使用Linux)。
It's somewhat what I wanted. But all I want is the equivalent of the pause
command in DOS/Windows (I use Linux).
推荐答案
从GNU C库手册:
功能:字符*与fgets(字符* S,诠释计数,FILE *流)
在与fgets
函数读取从流字符流直至并包括一个
换行符并将它们存储在字符串s,加入空
字符来标记串的结束。您必须提供数
价值在航天,,但字符的字符数读的是
顶多算 - 1 即可。额外的字符空间用于容纳空
字符在字符串的末尾。
The fgets function reads characters from the stream stream up to and including a newline character and stores them in the string s, adding a null character to mark the end of the string. You must supply count characters worth of space in s, but the number of characters read is at most count − 1. The extra character space is used to hold the null character at the end of the string.
因此,与fgets(键1,标准输入);
0读取字符和回报。 (阅读:立即)
So, fgets(key,1,stdin);
reads 0 characters and returns. (read: immediately)
使用的getchar
或函数getline
代替。
编辑:与fgets也不会返回一旦计数
字符都可以在流,它一直等待一个换行符,然后读取计数
字符,因此任意键可能不会在这种情况下,那么正确的写法。
fgets also doesn't return once count
characters are available on the stream, it keeps waiting for a newline and then reads count
characters, so "any key" might not be the correct wording in this case then.
您可以使用此<一个href=\"http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1042856625&id=1043284385\">example为避免线路缓冲:
You can use this example to avoid line-buffering:
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
int mygetch ( void )
{
int ch;
struct termios oldt, newt;
tcgetattr ( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr ( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr ( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
int main()
{
printf("Press any key to continue.\n");
mygetch();
printf("Bye.\n");
}
这篇关于等待在C用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!