简体   繁体   English

在while循环中控制getchar()

[英]Controlling getchar() in while loop

Say I have a simple while loop to enter **1*0* characters. 假设我有一个简单的while循环来输入** 1 * 0 *字符。 After more than 10, I want the loop to stop. 超过10之后,我希望循环停止。 However, the break seems not to take effect. 但是, break似乎没有生效。 Only when I press Enter it ends. 只有当我按Enter结束时。 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. stdin不是你的tty,即使你的tty连接到stdin。 Unless you put your tty in raw mode, the program does not see any data at all until you hit return. 除非你将你的tty置于原始模式,否则程序在你返回之前根本看不到任何数据。 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. 首先查看像ncurses这样的库,然后研究如何将tty放入原始模式。 And then write the simple program that requires the user to hit return. 然后编写需要用户点击返回的简单程序。

使用getch()getche()代替getchar()numchars=9代表10字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM