C 如何根据用户输入退出一段时间(1)?
我有一个简单的C 如何根据用户输入退出一段时间(1)?,c,while-loop,break,C,While Loop,Break,我有一个简单的服务器客户端终端。服务器从客户端接收字符串并对其进行处理。服务器只有在接收到输入字符的end\u后才会开始处理,在我的例子中,字符是&。下面的while循环旨在允许用户输入许多不同的字符串,并在接收到&时停止执行 while(1) { printf("Enter string to process: "); scanf("%s", client_string); string_size=strlen(client_string); //I want
服务器客户端
终端。服务器从客户端接收字符串并对其进行处理。服务器只有在接收到输入字符的end\u后才会开始处理,在我的例子中,字符是&
。下面的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循环在用户输入字符&
后退出
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
0
1
2
3
5
继续:
int i = 0;
while (1) {
if (i == 4) {
continue;
}
if (i == 6) {
break;
}
printf("%d\n", i++);
}
将打印:
0
1
2
3
0
1
2
3
5
只需在(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);
- break关键字可用于立即停止和转义循环
使用中断代码>…@SouravGhosh我尝试使用if(client_string[string_size]=='&')break;甚至没有运气,while(客户机字符串[string\u size-1]!='&')
对循环内部进行了一些重新安排…@Drgabble inC
while(1)
更可取。你在用java的方式思考
@xenteros啊,对不起,我还以为我试着用的是C++呢:if(client_string[string_size]=='&')break;没有luckuse if(客户端字符串[string\u size-1]=='&')中断@nanjeroechizen这是因为如果数组中有n个字母,则第n个字母的索引为n-1。请将答案标记为解决方案:)那么,如果用户只按enter键,而没有任何其他输入,会发生什么?我?是的,当然!;-)这将在任何&
上中断,无论字符串输入在何处。@Xentros您是怎么说的?