2017-10-06 6 views

답변

0

은 내가 잘못 없다면 당신은 그래서 1 제대로 n 개의 변수를 비교되지 않는다는 생각합니다. n과 1을 비교해보십시오.

int main() { 
int n; 
while (scanf("%d", &n) == 1){ 
    if(n!=1){ 
    break; 
    } 
    printf("%d\n",n); 
}  
return 0; 
} 

이것은 다소 엉뚱한 대답 일 수 있지만 예입니다.

+0

'scanf''EOF'이 돌아갈 수 있도록하는 부가하여 '경우 (N! = 1)'체크하여이'while' 조건 '이어야하지만 (는 scanf ("%의 D", N) == 1)'. – user694733

0

문제는 당신이 입력 읽기입니다 n의 값을 비교하는 것이 아니라, 당신이 가지고있는 입력의 수입니다 scanf 함수에 의해 반환되는 값은, 귀하의 경우 항상 1

때문이다 자세한 내용 : Value returned by scanf function in c

이 코드는 귀하의 경우 작동해야

: 입력의

#include<stdio.h> 

int main() { 
    int n; 
    scanf("%d", &n); 
    while(n == 1){ 
     printf("%d\n",n); 
     scanf("%d", &n); 
    } 
    return 0; 
} 
+1

여전히 반환 값을 확인해야합니다. 사용자가 잘못된 값을 입력하면 'n'의 초기화되지 않은 값을 읽습니다. – user694733

+0

또한'1 x'를 입력하면 어떻게되는지 생각해보십시오. –

1

scanf이 입력의 수를 반환이 및 할당 읽기 값이 아닌, 그 자체. 이 특별한 경우에는 하나의 입력만을 기대하기 때문에 scanf은 성공하면 1을, 일치하지 않으면 0을 반환합니다 (즉, 입력이 십진수로 시작하지 않음). 또는 EOF로 끝 점이 있으면 또는 오류. 당신이 입력 값에 대해 테스트하려면

, 당신은

while(scanf(“%d”, &n) == 1 && n == EXPECTED_VALUE) 
{ 
    printf(“%d”, n); 
} 

같은 편집을 할 줄

사실, 즉이 같은 것 할 수있는 더 좋은 방법 :

int n; 
int itemsRead; 

/** 
* Read from standard input until we see an end-of-file 
* indication. 
*/ 
while((itemsRead = scanf("%d", &n)) != EOF) 
{ 
    /** 
    * If itemsRead is 0, that means we had a matching failure; 
    * the first non-whitespace character in the input stream was 
    * not a decimal digit character. scanf() doesn't remove non- 
    * matching characters from the input stream, so we use getchar() 
    * to read and discard characters until we see the next whitespace 
    * character. 
    */ 
    if (itemsRead == 0) 
    { 
    printf("Bad input - clearing out bad characters...\n"); 
     while (!isspace(getchar())) 
     // empty loop 
     ; 
    } 
    else if (n == EXPECTED_VALUE) 
    { 
    printf("%d\n", n); 
    } 
} 

if (feof(stdin)) 
{ 
    printf("Saw EOF on standard input\n"); 
} 
else 
{ 
    printf("Error while reading from standard input\n"); 
}