0

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.

3
  • put the last ch=getchar() before break. Commented Nov 19, 2013 at 3:26
  • 1
    Your problem is that the first character is not read until the enter/return key is hit. You have to tweak the controls on your terminal (probably from within your program) to get characters as they are typed by the user. Commented Nov 19, 2013 at 3:31
  • Using setvbuf to turn off buffering may or may not fix this Commented Sep 11, 2014 at 6:47

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.