2012-09-29 4 views
0

순수 C으로 프로그램을 작성해야합니다. "(전 내가 입력scanf 사용자 입력 유효성 확인

int fillWithCustom(float *array, int size) { 
    float customNumber; 
    for (i = 0; i < size; i++) 
     for (j = 0; j < size; j++) {    
      printf("\n Enter [%d][%d] element: ", i , j); 
      scanf("%f", &customNumber); 
      *(array+i*size+j) = customNumber; 
     } 
    return 1; 
} 

을하지만 잘못된 번호 또는 문자를 입력 할 때, 반복 끝까지 계속됩니다. 나는 순간에서 사용자가 입력 수레와 배열 내 기능을 채우기 위해 할 것은 다음과 같다 는 "첫 번째 요소로, 다음 두 사이클는 scanf 년대없이 반복하고 배열 0 년대로 가득

답변

2

돈을, t는 사용자 입력을 scanf()를 사용합니다. 형식이 지정된 데이터와 함께 사용하도록 작성되었습니다. 사용자 입력 및 형식이 지정된 데이터는 야간과 다릅니다.

fgets()strtod()을 사용하십시오.

+0

감사합니다,이 올바른 기능을 좋은 포인터 않았다. 모두 잘 작동합니다. 나는 둘 다 대답하고 너를 받아 들인다. ;) –

1

scanf와의 리턴 값을 확인 scanf와의 사람이 페이지에서 :..

RETURN VALUE 
    These functions return the number of input items successfully matched 
    and assigned, which can be fewer than provided for, or even zero in the 
    event of an early matching failure. 

    The value EOF is returned if the end of input is reached before either 
    the first successful conversion or a matching failure occurs. EOF is 
    also returned if a read error occurs, in which case the error indicator 
    for the stream (see ferror(3)) is set, and errno is set indicate the 
    error. 

것은 독서를 유지하려면 데이터를 얻을 때까지 다음을 수행하십시오.

사용자가 잘못된 데이터의 할 일 입력하면 당신이 실패 할 경우
while(scanf("%f", &customNumber) == 0); 

:

if(scanf("%f", &customNumber) == 0) 
    break; 
+0

do {} {do not} do (do not는 errorno/* 여기에 * /를 무엇을 설정할 지 모르겠다.) ' 과 같이 오류를 발생시키지 않고 올바른 번호를 요청할 수 있습니까? –

+0

성공할 때까지 계속 시도하고 싶기 때문에 에러 번호는 0입니다. –