C:字符串比较

时间:2018-12-12 20:07:02

标签: c linux

bool done;
done = false;
while (!done) {
    /* read the message */
    bzero(msg, 100);
    printf("[client]Type something: ");
    fflush(stdout);
    read(0, msg, 100);
    if (strcmp(msg, "/done") == 0) {
        done = true;
        /* sending the message to the server */
        if (write(sd, msg, 100) <= 0) {
            perror("[client]Error sending the message to the server.\n");
            return errno;
        }
    } else {
        /* sending the message to the server */
        if (write(sd, msg, 100) <= 0) {
            perror("[client]Error sending the message to the server.\n");
            return errno;

        /* reading the answer given by the server*/
        if (read(sd, msg, 100) < 0) {
            perror("[client]read() error from server.\n");
            return errno;
        }
        /* printing the received message */
        printf("[client]The received message is: %s\n", msg);
    }
}

这是我有问题的代码。因此,我想将消息发送到服务器,直到我发送消息“ / done”,代码正常工作,我连续发送消息,但是即使我键入并发送“ / done”,该过程也不会结束。

我认为bzero函数有一个问题,它可以“清除”味精,或者我不太了解。

我还尝试编写自己的函数来检查两个字符串是否相同,但是也没有效果。

那么我应该如何写条件或“清除”消息,以便我可以连续发送消息,并且在发送“ /完成”之后执行结束?

P.S。 msg在代码中早先声明为char msg [100];

3 个答案:

答案 0 :(得分:0)

read(2)在字符串末尾包含'\ n'。当您使用低级读取时,您会得到所有。尝试调试字符串时,将引号放在打印语句中会很有帮助,例如

printf("[client]The received message is: '%s'\n", msg);

因为它立即显示不可见的空格。

答案 1 :(得分:0)

从0读取时,就是从stdin读取。如果这是您要输入的终端(您未说),则可能已将其设置为普通(规范)模式,因此您将读取一行,其中可能包含换行符(\ n)。因此,当您输入setAsyncStorage = () => { AsyncStorage.setItem("myKey", this.state.myKey); } <TextInput style={styles.formInput} onChangeText={text => this.saveData(text)} onSubmitEditing={this.setAsyncStorage} /> <Button title="Learn More" color="#841584" accessibilityLabel="Learn more about this purple button" onPress={this.setAsyncStorage} /> 时,您在msg缓冲区中得到的字符串是/done,它与"/done\n" ...

不匹配

答案 2 :(得分:0)

TCP不是消息协议。它不会将字节粘合在一起成为消息。如果要使用TCP发送和接收消息,则需要实现发送和接收消息的功能。

我必须强烈警告您,不要陷入这样的陷阱:认为将代码从尝试时不起作用改为尝试时就意味着您已修复代码。如果{ test: /\.js$/, exclude: /node_modules/, use: [ 'thread-loader', { loader: 'babel-loader'} ], }, { test: /\.ts(x?)$/, exclude: /node_modules/, use: [ { loader: 'thread-loader', }, { loader: 'babel-loader', }, { loader: 'ts-loader', options: { happyPackMode: true, } }, ], }, 返回1,则您的代码将失败。您需要实现一个明智的功能来接收消息,否则您的代码将只能靠运气工作,并且我可以从痛苦的经历中告诉您,有一天您的运气将耗尽。

相关问题