trama
trama

Reputation: 1401

How to get out of loop?

For a segment of my program, I am receiving a char array and checking if all the characters are ints.

When the other program doesn't send a string of ints, like asdf, it catches that. But then it cycles through the loop four times before exiting.

How can I continue out of this segment immediately after it reads that the first char is not an int? I've tried many things, but have been stuck with the same problem for a while. I feel like it's a simple fix.

EDIT: I'd like for it to only print the Incoming connection received and INVALID section one. Then continue from there.

    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;
    }

This is what the console displays:

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>

Upvotes: 1

Views: 279

Answers (1)

rhughes
rhughes

Reputation: 9583

You can use the break keyword.

For instance:

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 

Upvotes: 2

Related Questions