2017-01-28 39 views
0

假设我要求输入一个整数scanf(“%d”,&整数);.C - 如何检查是否有用户输入

我初始化整数变量像这样:int integer;

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

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

+1

在C中,未初始化的变量具有不确定的值。总是分配一个默认值是一种很好的做法,比如'int integer = 0'。 – bejado

+1

请阅读手册页中关于函数返回值的内容。 –

+1

请参阅scanf(...)的文档以了解它在没有输入时返回的内容 – Gab

回答

2
  1. 如果不输入任何内容,scanf将返回一个负值。

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

+0

感谢您的回答!我仍然对你所说的scanf负回报值感到困惑。 –

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'); 
} 

---------------------------------- 

IF想要使用scanf()然后检查返回的值(未参数值。)如果返回的值是1,则用户输入的整数值

相关问题