gpt4 book ai didi

c++ - 如何跳出循环?

转载 作者:行者123 更新时间:2023-11-30 04:08:41 26 4
gpt4 key购买 nike

对于我程序的一部分,我收到一个字符数组并检查是否所有字符都是整数。

当其他程序没有发送整型字符串时,例如 asdf,它会捕获它。但随后它在退出之前循环四次。

如何在读取到第一个字符不是整数后立即继续退出该段?我尝试了很多东西,但有一段时间一直被同样的问题困扰。我觉得这是一个简单的修复。

编辑:我希望它只打印收到的传入连接和无效的第一部分。然后从那里继续。

    int iRecvB = recv(acceptSocket, recvSerial, STRLEN, 0);
recvSerial[iRecvB] = '\0';
if (iRecvB > 0)
{
for (int n = 0; n < iRecvB; n++)
{
if (recvSerial[n] < '0' || recvSerial[n] > '9')
{
isNumber = false;
}
if (!isNumber)
{
int iSend = send(acceptSocket, "no", 2, 0);
cout << "\nIncoming connection received.\n" << "Data received:" << endl;
cout << "\tSerial: " << recvSerial << endl;
cout << "\t INVALID\n" << endl;
if (iSend == SOCKET_ERROR)
{
cerr << "ERROR: Failed to send message11111\n";
cleanup(acceptSocket);
return 1;
}
}
}// END OF FOR LOOP FOR NUM CHECK
}
else if (iRecvB == 0)
{
cout << "Connection closed\n";
cleanup(acceptSocket);
return 0;
}
else
{
cerr << "ERROR: Failed to receive message\n";
cleanup(acceptSocket);
return 1;
}

这是控制台显示的内容:

Incoming connection received.
Data received:
Serial: asdf
INVALID


Incoming connection received.
Data received:
Serial: asdf
INVALID


Incoming connection received.
Data received:
Serial: asdf
INVALID

ERROR: Failed to send message11111

C:\Users\Admin\Desktop\Activation\ActivationServer\Debug>

最佳答案

您可以使用 break 关键字。

例如:

for (int n = 0; n < iRecvB; n++)
{
if (recvSerial[n] < '0' || recvSerial[n] > '9')
{
isNumber = false;
}
if (!isNumber)
{
int iSend = send(acceptSocket, "no", 2, 0);
cout << "\nIncoming connection received.\n" << "Data received:" << endl;
cout << "\tSerial: " << recvSerial << endl;
cout << "\t INVALID\n" << endl;
if (iSend == SOCKET_ERROR)
{
cerr << "ERROR: Failed to send message11111\n";
cleanup(acceptSocket);
return 1;
}

break; // <-- HERE
}
}// END OF FOR LOOP FOR NUM CHECK

关于c++ - 如何跳出循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21694144/

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