2017-01-28 40 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,則用戶輸入的整數值

相關問題