별의 공부 블로그 🧑🏻‍💻

scanf와 ' '(공백)

Programming/C 2017. 8. 31. 14:21
728x90
728x170

 

I wonder why scanf wants to get one more than the number of 'num' when I use this function for array index with infinite loop.

5 // The number of the index of an array.

1 2 3 4 5 // I put 5 numbers because I set the number of the index as 5. but..

6 // I had to put another number to finish the work of scanf.

1 2 3 4 5 // The numbers in the array. 6 has disappeared.

Here is a code that I made to test.

#include <stdio.h>

int main()
{
    int num = 0;
    int n[100000] = { 0 };

    while (1) {
        scanf("%d ", &num);     

        if (num > 100000 || num <= 0) {
            printf("Input a number again. \n");
        }

        else {
            for (int i = 0; i < num; i++) {
                scanf("%d ", &n[i]);
            }

            // Test
            for (int k = 0; k < num; k++) {
                printf("%d ", n[k]);
            }

            break;
        }
    }

    return 0;
}

 

scanf를 사용할 때, 입력 받는 부분에 ' '(공백)을 둘 경우 입력을 한 번 더 받는 현상 발생한다.

이러한 현상이 발생하는 이유는 아래와 같다.

 

 From my scanf manual page

White space (such as blanks, tabs, or newlines) in the format string match any amount of white space, including none, in the input. Everything else matches only itself.

 Thus with scanf ("%s\n", a) it will scan for a string followed by optional white space. Since after the first newline more whitespace may follow, scanf is not done after the first newline and looks what's next. You will notice that you can enter any number of newlines (or tabs or spaces) and scanf will still wait for more.

 However, when you enter the second string, the sequence of whitespace is delimited and scanning stops.

 

Source from : https://stackoverflow.com/questions/15740024/scanf-asking-twice-for-input-while-i-expect-it-to-ask-only-one

728x90
그리드형(광고전용)
⚠️AdBlock이 감지되었습니다. 원할한 페이지 표시를 위해 AdBlock을 꺼주세요.⚠️
starrykss
starrykss
별의 공부 블로그 🧑🏻‍💻


📖 Contents 📖