문제

Say I have a simple while loop to enter **1*0* characters. After more than 10, I want the loop to stop. However, the break seems not to take effect. Only when I press Enter it ends. Can anyone explain please?

int count = 0;
int numchars = 10;
ch = getchar();
while( ch != '\n' && ch != '\0' ) {     
    array[count] = ch;
    count++;    
    if ( count > numchars ){        
        break;          
    }
    ch = getchar(); 
}

Thanks.

도움이 되었습니까?

해결책

stdin is not your tty, even when your tty is connected to stdin. Unless you put your tty in raw mode, the program does not see any data at all until you hit return. When you hit return, all of the data on the line is sent to the program, which then enters the loop and reads characters until it breaks out of the loop. If you really want the program to see characters as you press them, you will need to do a lot more work. Look into libraries like ncurses first, and then do some research on how to put a tty into raw mode. And then write the simple program that requires the user to hit return.

다른 팁

use getch() or getche() instead of getchar() and numchars=9 for 10 characters.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top