nanjero echizen
nanjero echizen

Reputation: 231

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 processes it. The server will only start processing once it receives the end_of_input character which in my case is '&'. The while loop below is meant to allow a user to input a number of different strings and should stop performing as it receives '&'.

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 '&'?

Upvotes: 2

Views: 3255

Answers (3)

sakthi
sakthi

Reputation: 705

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

    string_size=strlen(client_string);

    if (client_string[string_size - 1] == '&')
        break;
    write(csd, client_string, string_size);
}
  • break keyword can be used for immediate stopping and escaping the loop.

Upvotes: 1

alk
alk

Reputation: 70981

Just drop this while(1) statement. You want to happen the scanning at least once, so use a do-while() construct instead:

#define END_OF_INPUT '&'

...


do 
{
  printf("Enter string to process: \n");
  scanf("%s", client_string);

  string_size = strlen(client_string);
  write(csd, client_string, string_size);
} while ((string_size > 0) && /* Take care to not run into doing client_string[0 - 1] */
         (client_string[string_size - 1] != END_OF_INPUT));

In case the stopper should not be sent:

int end_of_input = 0;

do 
{
  printf("Enter string to process: \n");
  scanf("%s", client_string);

  string_size = strlen(client_string);

  end_of_input = (string_size > 0) && (client_string[string_size - 1] == END_OF_INPUT);
  if (end_of_input)
  {
    client_string[string_size - 1] = `\0`;
  }

  write(csd, client_string, string_size);
} while (!end_of_input);

Upvotes: 1

xenteros
xenteros

Reputation: 15862

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

Upvotes: 7

Related Questions