2017-04-20 20 views
0

scanf("[^\n]s", x) 또는 "%34[^\n]" 또는 %127s에이 조건을 사용하더라도 정확한 답변을 얻을 수 없습니다. scanf 영역 또는 일부 다른 부분에 문제 .... 그런scanf로 공백을 읽는 방법

#include <stdio.h> 

int main() 
{ 
    int i = 4; 
    double d = 4.0; 
    char s[] = "hello "; 
    int a; 
    double b; 
    unsigned char string_2[100]; 
    scanf("%d",&a); 
    scanf("%lf",&b); 
    scanf("%[^\n]s",string_2); 
    printf("%d",a+i); 
    printf("\n%lf",d+b); 
    printf("\n%s",s); 
    printf("%s",string_2); 
    return(0); 
} 
사용하지 마십시오
+2

'는 scanf ("% lf를"을 &b); 는 scanf를 ("% "% 99 [^ \ n]", while (getchar()! = '\ n'), scanf ("% lf", string_2) string_2); ' – BLUEPIXY

+0

그래, 그 남자 일 했어 ... awsome ....... – Nivethithan

답변

1

scanf이있다. 이에

:

scanf("%lf",&b); 
scanf("%[^\n]s",string_2); 

첫 번째 scanf 입력에서 번호를 읽지 만 터미널 먼저 프로그램을 입력의 전체 라인을 제공하기 위해 기다려야합니다. 사용자가 123이라고 가정하고 프로그램이 OS에서 123\n을 읽습니다.

scanf

더이상 수의 일부가 아닌 개행을보고하고 (표준 입출력 이내) 입력 버퍼에서 개행 떠나는 것을 에서 정지한다. 두 번째 scanf은 줄 바꿈이 아닌 내용을 읽으려고 시도하지만 할 수 없습니다. 첫 번째 내용은 줄 바꿈입니다. scanf 호출의 반환 값을 확인하면 두 번째 scanf가 0을 반환한다는 것을 알 수 있습니다. 즉, 요청한 변환을 완료 할 수 없습니다. 참조 더 긴 토론을위한

#include <stdio.h> 
int main(void) 
{ 
    char *buf = NULL; 
    size_t n = 0; 
    double f; 
    getline(&buf, &n, stdin); 
    if (sscanf(buf, "%lf", &f) == 1) { 
     printf("you gave the number %lf\n", f); 
    } 
    getline(&buf, &n, stdin); 
    printf("you entered the string: %s\n", buf); 
    return 0; 
} 

:

는 대신, fgets 또는 getline으로, 한 번에 전체 라인을 읽을 http://c-faq.com/stdio/scanfprobs.html