Reputation: 1243
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.
Upvotes: 0
Views: 1125
Reputation: 45
use getch()
or getche()
instead of getchar()
and numchars=9
for 10
characters.
Upvotes: 0
Reputation: 212198
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.
Upvotes: 2