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

寵の児 提交于 2019-12-11 01:46:50

问题


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


回答1:


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



回答2:


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



回答3:


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.


来源:https://stackoverflow.com/questions/38913603/how-can-i-exit-a-while1-based-on-a-user-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!