gpt4 book ai didi

c - 在 C 中用键盘打破 FOR 循环

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:35 26 4
gpt4 key购买 nike

我有一个程序在开始 for (;;) 循环之前运行几个步骤。

我要能破;此 for 循环使用击键(例如 'e' 退出)

我试过 scanf_s 但我认为我没有正确使用它们。如果我尝试写入 scanf_s ,循环就不会启动。

我对 C 编程不是很熟悉,所以我有点吃力。

有人可以阐明这一点吗?

额外信息:

操作系统为Win 8.1。

程序是一个TCP服务器程序。它创建一个套接字并开始监听。然后它开始在 for 循环中接受客户端连接。然后开始另一个 for 循环以接收来自客户端的消息。

编辑:使用 this我已经设法用 s 停止了第二个 for 循环。添加了对简化代码的更改(如下所示)。

添加:

if (_kbhit()) {
key = _getch();
if (key == 's');
break;
}

这里是一些简化的代码:

#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
// prelim info goes here
// like SOCKET
// and struct sockaddr_in

// Initialize Winsock
WSAStartup();

// Create socket
mysocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

// server parameters go here
// like sin_addr and sin_port

bind(mysocket);

// start listening
listen(mysocket, SOMAXCONN);

// begin the damn for loops

for (;;)
{

myclient = accept();

//second for loop
for (;;)
{
receivedata = recv(myclient);

printf(<data>)

if (_kbhit()) {
key = _getch();
if (key == 's');
break;
}

}
}

// close socket
closesocket(mysocket);

// call WSACleanup
WSACleanup();

return 0;
}

感谢所有提供链接和有用答案的人。事实证明,外循环的问题比破坏它要复杂得多。然而,如果任何 future 的访问者想知道如何通过键盘按下来打破循环,这已经实现了。请参阅正确答案或我的简化代码。

最佳答案

您可以尝试使用 kbhitgetchar 来检查击键并相应地处理操作。查看此帖子:Return pressed key without enter for confirmation

当按下 e 时,这段代码会中断 while 循环:[代码更新了一个额外的 while 循环]

#include <stdio.h>
#include <conio.h>

int main(){
int ch = '1';
while(ch != 'e'){ //outer while for accepting connection
printf("waiting for connection\n"); //do something

while(ch != 'e'){ //inner while for checking key press
if(kbhit()) //if key is pressed
ch = getch(); //get the char and set ch to 'e'
}
}

return 0;
}

使用 break 的旧代码:

#include <stdio.h>
#include <conio.h>
#include <windows.h>
int main(){
int ch;
while(1){
printf("*");
if(kbhit()){ //if key is pressed
ch = getch(); //get the char
if(ch == 'e') //if pressed key is 'e'
break; //break while loop
}
}

return 0;
}

关于c - 在 C 中用键盘打破 FOR 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25946367/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com