我想创建一个 while 循环,不断要求用户输入,直到用户 ctrl-d 退出。我怎样才能正确地做到这一点?我现在正在使用这个:
while (1)
{
printf("Enter host name: ");
fgets(user_input, 1000, stdin);
}
这有效,但用户必须按 ctrl-c 才能结束程序。我想不断询问用户输入,直到他/她点击 ctrl-d。我怎样才能做到这一点?
最佳答案
您必须测试 EOF,这是 CTRL-D 返回的内容。
所以这样做:
while ( fgets( ... ) != NULL ) {
...
}
编辑:
既然你在提示,那就更好了:
for ( ;; ) {
printf( "enter input: " );
fflush( NULL ); // make sure prompt is actually displayed, credit Basile Starynkevitch
if ( fgets( input, ... ) == NULL ) break;
// handle input here
}
关于c - while循环要求输入直到使用C的ctrl-d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25770335/