2017-08-10 9 views
-2

私はあなたがcでユーザ入力を検証する方法を知りたいのですが、ユーザが座標を入力する必要があります.1から8までの整数を(1-8)から別の整数、例えば "1,1"で区切ります。 strtok()またはstrtol()を使ってこれを行うことができるかどうか疑問に思っていましたか?cでユーザー入力を検証する方法は?

答えて

1

入力フォーマットが固​​定されている場合、strtok()strtol()を使用するよりも、入力を解析するために、入力の行を取得するにはfgets()を使用し、sscanf()するはるかに簡単です。

ここでは、ユーザーが[1,8]の範囲に2つの整数を入力することを検証する例を示します。ユーザーが2つ以下の値を入力した場合、または値が範囲外である場合、または許容値の後に余分な入力がある場合は、別の座標ペアを入力するように求められます。

#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

ありがとう –

関連する問題