C - 如何检查是否有用户输入

时间:2017-01-28 20:42:16

标签: c

假设我要求整数输入,例如scanf("%d",& integer);.

我初始化了整数变量,如下所示:int integer;

问题 - 1:如果用户什么都没输入,我怎么知道?

问题 - 2:初始化整数变量(int integer;)后,整数包含什么?

2 个答案:

答案 0 :(得分:2)

  1. 如果您没有输入任何内容,scanf将返回负值。

    int integer; 
    int result = scanf("%d", &integer);
    if (result > 0) { /* safe to use integer */ }
    
  2. int integer;初始化为程序为其分配的位置的数据。因此它看起来像垃圾,应该使用合理的值进行初始化,例如0

答案 1 :(得分:0)

来自:https://gcc.gnu.org/ml/gcc-help/2006-03/msg00101.html

for status in timeline:
    if hasattr(status, 'quoted_status'):
        print (status.quoted_status)
    else:
        print ("null")

如果想要使用/* --- 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'); } ---------------------------------- ,则检查返回的值(而不是参数值。)如果返回的值为1,则用户输入整数值