[英]C - How to check if there is a user input
假設我要問一個整數輸入,例如scanf(“%d”,&integer);。
我像這樣初始化整數變量:int integer;
問題-1:如果用戶什么都不輸入,我怎么知道?
問題-2:初始化整數變量(int integer;)之后,整數包含什么?
如果您不輸入任何內容, scanf
將返回負值。
int integer; int result = scanf("%d", &integer); if (result > 0) { /* safe to use integer */ }
int integer;
被初始化為程序分配給它的位置處的數據。 因此,它將看起來像垃圾,應使用諸如0
的合理值進行初始化。
這是來自: https : //gcc.gnu.org/ml/gcc-help/2006-03/msg00101.html
/* --- self-identity --- */
#include "kbhit.h"
/* fileno setbuf stdin */
#include <stdio.h>
/* NULL */
#include <stddef.h>
/* termios tcsetattr tcgetattr TCSANOW */
#include <termios.h>
/* ioctl FIONREAD ICANON ECHO */
#include <sys/ioctl.h>
static int initialized = 0;
static struct termios original_tty;
int kbhit()
{
if(!initialized)
{
kbinit();
}
int bytesWaiting;
ioctl(fileno(stdin), FIONREAD, &bytesWaiting);
return bytesWaiting;
}
/* Call this just when main() does its initialization. */
/* Note: kbhit will call this if it hasn't been done yet. */
void kbinit()
{
struct termios tty;
tcgetattr(fileno(stdin), &original_tty);
tty = original_tty;
/* Disable ICANON line buffering, and ECHO. */
tty.c_lflag &= ~ICANON;
tty.c_lflag &= ~ECHO;
tcsetattr(fileno(stdin), TCSANOW, &tty);
/* Decouple the FILE*'s internal buffer. */
/* Rely on the OS buffer, probably 8192 bytes. */
setbuf(stdin, NULL);
initialized = 1;
}
/* Call this just before main() quits, to restore TTY settings! */
void kbfini()
{
if(initialized)
{
tcsetattr(fileno(stdin), TCSANOW, &original_tty);
initialized = 0;
}
}
----------------------------------
To use kbhit:
----------------- demo_kbhit.c -----------------
/* gcc demo_kbhit.c kbhit.c -o demo_kbhit */
#include "kbhit.h"
#include <unistd.h>
#include <stdio.h>
int main()
{
int c;
printf("Press 'x' to quit\n");
fflush(stdin);
do
{
if(kbhit())
{
c = fgetc(stdin);
printf("Bang: %c!\n", c);
fflush(stdin);
}
else usleep(1000); /* Sleep for a millisecond. */
} while(c != 'x');
}
----------------------------------
如果要使用scanf()
則檢查返回的值(而不是參數值)。如果返回的值是1,則用戶輸入了一個整數值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.