如何根据用户输入退出一会儿(1)? [英] How can I exit a while(1) based on a user input?

查看:71
本文介绍了如何根据用户输入退出一会儿(1)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的服务器-客户端终端。服务器从客户端接收字符串并对其进行处理。服务器仅在收到 end_of_input 字符(在我的情况下为'&')后才开始处理。下面的while循环旨在允许用户输入许多不同的字符串,并且应该在接收到'&'时停止执行。

I have a simple server-client terminals. The server receives strings from the client and processes it. The server will only start processing once it receives the end_of_input character which in my case is '&'. The while loop below is meant to allow a user to input a number of different strings and should stop performing as it receives '&'.

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

如何做到这一点,以便在用户输入输入的结尾字符'&'

How could I make it so that the while loop exits after a user inputs the end_of_input character '&'?

推荐答案

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;
    }
}

休息关键字可用于立即停止和转义循环。大多数编程语言都使用它。
还有一个有用的关键字可以稍微影响循环处理: continue

break keyword can be used for immediate stopping and escaping the loop. It is used in most of programming languages. There is also one useful keyword to slightly influence loop processing: continue. It immediately jumps to the next iteration.

示例

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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆