nanjero echizen nanjero echizen - 3 months ago 8
C Question

How can I exit a while(1) based on a user input?

I have a simple server-client terminals. The server receives strings from the client and process it. The server will only start processing once it receives the

end_of_input
character
'&'
. The while loop below is meant to allow a user to input a number of different strings.

while(1) {
printf("Enter string to process: ");
scanf("%s", client_string);

string_size=strlen(client_string);
//I want to escape here if client_string ends with '&'
write(csd, client_string, string_size);
}


How could I make it so that the while loop exits after a user inputs the
end_of_input
character
'&'
?

Answer
while(1) {
    printf("Enter string to process: ");
    scanf("%s", client_string);

    string_size=strlen(client_string);
    write(csd, client_string, string_size);
    if (client_string[string_size -1 ] == '&') {
        break;
    }
}

break keyword can be used for immediate stopping and escaping the loop. It is used in most of programming languages. There is also one useful keyword to slightly influence loop processing: continue. It immediately jumps to the next iteration.

Examples:

int i = 0;
while (1) {
    if (i == 4) {
        break;
    }
    printf("%d\n", i++);
}

will print:

0
1
2
3

Continue:

int i = 0;
while (1) {
    if (i == 4) {
        continue;
    }
    if (i == 6) {
        break;
    }
    printf("%d\n", i++);
}

will print:

0
1
2
3
5
Comments