I have a program that runs through a few steps before it starts a for (;;)
loop.
I want to be able to break; this for
loop using a keystroke (such a 'e
' for exit, for example)
I've tried scanf_s
but I don't think I am using them correctly. the loop just doesn't initiate if I try to write scanf_s
in.
I'm not very familiar with C programming so I'm struggling a little bit.
Can someone shed some light on this?
extra info:
Operating system is Win 8.1.
Program is a TCP server program. it creates a socket and begins listening. Then it starts accepting client connections in a for
loop. then begins another for
loop to receive messages from the client.
Edit: using this I have managed to stop the second for loop with s
. added the changes to the simplified code (and just bellow).
added:
if (_kbhit()) {
key = _getch();
if (key == 's');
break;
}
here is some simplified code:
#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;
}
thanks to everyone who supplied links and the helpful answers. The issue with the outer loop turned out to be a bit more involved than just breaking it. However, if any future visitors are wondering how to break a loop with a keyboard press, this has been achieved. See the correct answer or my simplified code.