2013-03-05 75 views
1
#include "stdafx.h" 
#include <stdlib.h> 

void main() 
{ 
    char buffer[20]; 
    int num; 

    printf("Please enter a number\n"); 
    fgets(buffer, 20, stdin); 
    num = atoi(buffer); 

    if(num == '\0') 
    { 
     printf("Error Message!"); 
    } 

    else 
    { 
     printf("\n\nThe number entered is %d", num); 
    } 

    getchar(); 
} 

上述代碼接受一個字符串形式的數字,並使用atoi將其轉換爲整數。如果用戶輸入一個十進制數,則只接受小數點前的位。此外,如果用戶輸入一個字母,則返回0。使用atoi()輸入驗證整數使用atoi()

現在,我有兩個查詢:

ⅰ)我想要的程序以檢測是否用戶輸入的號碼與小數點和輸出的錯誤信息。我不希望它在小數點之前採取部分。我希望它認識到輸入無效。 ii)如果atoi在有字母的情況下返回0,那麼我怎樣才能驗證它,因爲用戶也可以輸入數字0?

謝謝。

+1

也許複製http://stackoverflow.com/questions/8871711/atoi-how-to-identify-the的零和錯之間的差距 – Xymostech 2013-03-05 16:45:50

+0

你想要什麼?爲了確保用戶輸入一個整數或知道用戶是否輸入一個浮點數? - 檢查ctype.h。它有一些函數isnumber(),isdigit()等等。 – 2013-03-05 16:50:04

+4

'printf(「錯誤信息」)'*總是*錯誤。你的意思是'fprintf(stderr,「錯誤信息」)'。錯誤屬於'stderr'。輸出「stdout」。 – 2013-03-05 16:51:04

回答

6

atoi不適合錯誤檢查。改爲使用strtolstrtoul

#include <errno.h> 
#include <limits.h> 
#include <stdlib.h> 
#include <string.h> 

long int result; 
char *pend; 

errno = 0; 
result = strtol (buffer, &pend, 10); 

if (result == LONG_MIN && errno != 0) 
{ 
    /* Underflow. */ 
} 

if (result == LONG_MAX && errno != 0) 
{ 
    /* Overflow. */ 
} 

if (*pend != '\0') 
{ 
    /* Integer followed by some stuff (floating-point number for instance). */ 
} 
+2

「不是非常sutiable」是一個*巨大*輕描淡寫! – 2013-03-05 16:50:01

+0

@WilliamPursell:更安全,更多工作,更多代碼!你不會繞過它。在它周圍放置一個包裝將其縮回到正常狀態。 – alk 2013-03-05 17:32:03

0

還有就是isdigit功能,可以幫助您檢查每個字符:

#include <ctype.h> 

/* ... */ 

for (i=0; buffer[i]; i++) { 
     if (!isdigit(buffer[i])) { 
      printf("Bad\n"); 
      break; 
     } 
}