如何根据用户输入退出 while(1)?

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

我有一个简单的 server-client 终端。服务器从客户端接收字符串并进行处理。服务器只有在收到 end_of_input 字符后才会开始处理,在我的例子中是 '&'。下面的 while 循环旨在允许用户输入多个不同的字符串,并且应该在收到 '&'.

时停止执行
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);
}

我怎样才能使 while 循环在用户输入 end_of_input 字符 '&' 后退出?

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 关键字可用于立即停止和退出循环。它用于大多数编程语言。 还有一个对循环处理有轻微影响的有用关键字:continue。它立即跳转到下一个迭代。

例子:

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

将打印:

0
1
2
3

继续:

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

将打印:

0
1
2
3
5

只需删除此 while(1) 语句。您希望至少进行一次扫描,因此请改用 do-while() 结构:

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

如果不应该发送塞子:

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] = `[=11=]`;
  }

  write(csd, client_string, string_size);
} while (!end_of_input);
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 关键字可用于立即停止和退出循环。