2017-08-10 22 views
-2

我想知道你將如何去驗證c中的用戶輸入,我需要用戶輸入座標,從(1-8)中分隔另一個整數的整數(1-8),例如「1,1」。我想知道是否可以使用strtok()或strtol()來做到這一點?如何驗證c中的用戶輸入?

回答

1

如果輸入格式是固定的,它是非常容易使用fgets()得到一個線路輸入,然後sscanf()解析輸入,而不是使用strtok()strtol()

下面是一個驗證用戶在範圍[1,8]中輸入兩個整數的示例。如果用戶輸入的值少於兩個值,或者值超出範圍,或者在接受值之後有額外輸入,則提示用戶輸入另一對座標。

#include <stdio.h> 
#include <stdlib.h> 

int main(void) 
{ 
    char buffer[100]; 
    int x, y; 

    /* sscanf() method: input must be comma-separated, with optional spaces */ 
    printf("Enter a pair of coordinates (x, y): "); 
    if (fgets(buffer, sizeof buffer, stdin) == NULL) { 
     perror("Input error"); 
     exit(EXIT_FAILURE); 
    } 

    int ret_val; 
    char end; 
    while ((ret_val = sscanf(buffer, "%d , %d%c", &x, &y, &end)) != 3 
      || x < 1 
      || x > 8 
      || y < 1 
      || y > 8 
      || end != '\n') { 
     printf("Please enter two coordinates (x, y) in the range [1, 8]: "); 
     if (fgets(buffer, sizeof buffer, stdin) == NULL) { 
      perror("Input error"); 
      exit(EXIT_FAILURE); 
     } 
    } 

    printf("You entered (%d, %d).\n", x, y); 

    return 0; 
} 
+0

非常感謝 –