我有一个简单的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
如何在用户输入'&'
字符example:
后退出while循环?
答案 0 :(得分:7)
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
答案 1 :(得分:1)
只需删除此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);
答案 2 :(得分:1)
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);
}