2013-12-15 29 views
1

嗨,我希望能夠對我的數據輸入到我的結構'數據包'上的'數據'條目進行一些驗證。C編程 - 檢查字符,並停止數組超過50個字符長

基本上它只能有50個字符長,只有數字輸入。

struct packet{ // declare structure for packet creation 
    int source; 
    int destination; 
    int type; 
    int port; 
    char data[50]; 
}; 

struct packet list[50]; //Array for structure input & initiate structure 

printf("\nEnter up to 50 numeric characters of data.\n"); 
scanf("%s", list[x].data); 

所有的幫助是有用的,我提前感謝你。

+1

從什麼寫這樣的代碼將停止嗎?什麼似乎很難? –

+0

我目前在大學攻讀C,所以我不是100%的C語言高效。我對我想做什麼有了一些想法,但並不知道如何去做。 – user3103598

回答

2

使用此:

scanf("%49s", list[x].data); 

需要49而非50,因爲空終止將被添加。

一旦你有你的角色,使用isdigit()來執行有效性檢查。

2

增加您的目的地的尺寸或更多50 char\0。使用格式"%50[0-9]"說明符。

struct packet{ // declare structure for packet creation 
    ... 
    char data[51]; 
}; 
// it can only be 50 characters long and only have number inputs 
if (scanf("%50[0-9]", list[x].data) != 1) Handle_Unexpected_Input(); 
if (strlen(list[x].data) < 50)) String_Too_Short(); 

您可能需要一個前導空格丟棄前導空格:" %50[0-9]"

相關問題