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

我有一个简单的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); } 

我怎么能这样做,以便在用户输入end_of_input字符'&'后,while循环退出?

 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] = `\0`; } 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关键字可用于立即停止和转义循环。