0

I made a code that inputs four letters, and prints an '*' in place of each one, as in a password. The working code is this:

#include <stdio.h>
#include <conio.h>
int main()
{
    int c = 0;
    char d[4];
    printf("Enter a character:");
    while (1)
    {
        if (_kbhit())
        {
            d[c] = _getch();
            printf("*");
            c++;
        }
        if (c == 4)
            break;
    }
    system("cls");
    for (c = 0; c <= 3; c++)
        printf("%c", d[c]);
}

Now I have two questions: 1) Why do I get four ╠'s when I change the loop to:

for (c = 0; c <= 4;c++)
    {
        if (_kbhit())
        {
            d[c] = _getch();
            printf("*");
        }
    }

and 2) Why do I get an extra ╠ at the end when I change the second loop's upper limit to c<=4?

The second loop being this:

for (c = 0; c <= 3; c++)
        printf("%c", d[c]);
4

1 回答 1

0

导致for无论_kbhit()返回 true 还是 false,循环都会迭代 4 次。while循环直到_kbhit()返回 true 4次

对于第二个问题,d[4]是否超出了数组的范围,相同的值只是巧合

于 2015-12-18T17:49:39.037 回答