#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?
謝謝。
也許複製http://stackoverflow.com/questions/8871711/atoi-how-to-identify-the的零和錯之間的差距 – Xymostech 2013-03-05 16:45:50
你想要什麼?爲了確保用戶輸入一個整數或知道用戶是否輸入一個浮點數? - 檢查ctype.h。它有一些函數isnumber(),isdigit()等等。 – 2013-03-05 16:50:04
'printf(「錯誤信息」)'*總是*錯誤。你的意思是'fprintf(stderr,「錯誤信息」)'。錯誤屬於'stderr'。輸出「stdout」。 – 2013-03-05 16:51:04