1. 程式人生 > >只允許輸入正整數

只允許輸入正整數

       在解析TS流檔案時,我要實現輸入節目號就能顯示節目相關資訊,但是我剛開始沒有判斷輸入的節目號是不是正整數,我不小心按了其他鍵就一樣會被識別,但是沒有資訊,這可不行,萬一使用者按錯了鍵,但還是跳轉到了節目資訊節目,顯示空白,使用者可就生氣。

     我的實現方法是先定義個數組,然後逐位比較是不是0~9的數字,這可通過isdigit()函式來實現,全部判斷完再通過atoi()函式轉換一下給一個變數,就完成了,因為我需要的是正整數和輸入0就退出,所以程式就是這樣的。

int i = 0;
char a[10] = { 0 };
unsigned int uiServiceId = 0; 


while(1)
{
    prf_dem("please enter program number(exit 0):");
    scanf("%s",a);
    for(i = 0; a[i] != 0; i++)
    {
        if(isdigit(a[i]) == 0)
	{
	    if(i == 0 && a[i] == 0)
	    {
		break;
	    }
	    prf_dem("please enter positive integer!!!!!!\n");
	    prf_dem("please enter program number(exit 0):");
	    scanf("%s",a);
	    break;
	}
    }
		
    uiServiceId = atoi(a);
    if(uiServiceId)
    {
     /* parse EIT information*/
  iReturn =ParseAllEitSection(stTransportParameter,pfTsFile,iTsPosition,uiServiceId);
        if(iReturn == -1)
        {
            printf("Fail to ParseAllEitSection!!!\n");
            return iReturn;
        }
    }
    else
    {
	break;
    }
}