我是編程和C的新手,目前正在大學學習。這是一個任務,所以我想避免直接的答案,但更多的技巧或提示/推後正確的方向。使用strtol驗證整數輸入ANSI C
我想使用strtol來驗證我的鍵盤輸入,更具體地說,測試輸入是否是數字。我查看了其他網站和其他網站上的其他問題,並按照其他用戶的說明進行了操作,但這並沒有幫助我。
從我讀/理解strtol將的(長整型與strtol(爲const char *海峽,字符** endptr,INT基地);)如果endptr是不是一個空指針的函數將設置數值後的第一個字符的值爲endptr。
因此,如果我要輸入84948ldfk,endptr將指向'l',告訴我在輸入中有數字以外的字符,並且會使其無效。
但在我的情況下,發生了什麼事情,無論我輸入什麼,我的程序都返回一個無效輸入。這裏是我的代碼:
void run_perf_square(int *option_stats)
{
char input[MAX_NUM_INPUT + EXTRA_SPACES]; /*MAX_NUM_INPUT + EXTRA_SPACES are defined
*in header file. MAX_NUM_INPUT = 7
*and EXTRA_SPACES
*(for '\n' and '\0') = 2. */
char *ptr;
unsigned num=0; /*num is unsigned as it was specified in the start up code for the
*assignment. I am not allow to change it*/
printf("Perfect Square\n");
printf("--------------\n");
printf("Enter a positive integer (1 - 1000000):\n");
if(fgets(input, sizeof input, stdin) != NULL)
{
num=strtol(input, &ptr, 10);
if(num > 1000001)
{
printf("Invalid Input! PLease enter a positive integer between 1
and 1000000\n");
read_rest_of_line(); /*clears buffer to avoid overflows*/
run_perf_square(option_stats);
}
else if (num <= 0)
{
printf("Invalid Input! PLease enter a positive integer between 1
and 1000000\n");
run_perf_square(option_stats);
}
else if(ptr != NULL)
{
printf("Invalid Input! PLease enter a positive integer between 1
and 1000000\n");
run_perf_square(option_stats);
}
else
{
perfect_squares(option_stats, num);
}
}
}
任何人都可以幫助我在正確的方向嗎?顯然,錯誤是與我的如果(ptr!= NULL)條件,但據我瞭解,似乎是正確的。正如我所說,我已經看過以前的類似問題,並在答案中提出了建議,但它似乎並不適用於我。因此,我認爲最好能夠根據我自己的情況尋求我的幫助。
在此先感謝!
編輯:好的我得到它的工作,並經過一些測試後,似乎工作正常。我的if語句是個問題。下面的代碼爲我工作至今:
if((input[0] != '\n' && (*ptr == '\0' || *ptr == '\n')) && num < 1000001 && num > 0)
{
perfect_squares(option_stats, num);
}
else
{
printf("Invalid Input! PLease enter a positive integer between 1
and 1000000\n");
if(num > 1000001)
{
read_rest_of_line();
}
run_perf_square(option_stats);
}
我可能會清理if語句,使之少一些混亂,但對結果滿意爲止。
'否則如果(NUM <= 0)' – chux
您好chux,我的輸入必須是大於0,不能等於它。 – Lukaaaaaaaay
'else if(num <= 0)'_is_您的錯誤情況。 – chux