我有一个简单的 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
关于c - 如何根据用户输入退出 while(1)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38913603/