c - If 语句中使用的字符串指针不起作用

标签 c string pointers strtok

使用 strtok 解析字符串,现在我的 IF 语句遇到了困难。怀疑我使用了错误的案例(值(value)与地址),但我已经没有想法了。任何帮助将不胜感激。

我使用一系列 printf 来确认 strtok 正确填充了“hldType”。再次感谢任何帮助。我已经坚持了好几天了。

缩写代码如下。还包括完整的代码源。

char *hldType;                        /* Parsing holding field */
static const char *REQTYPE = "0";     /* Comparison */

hldType = strtok(echoBuffer, ".");    /* Parse the string */
if (strcmp(hldType,REQTYPE)  == 0)    /* NOT WORKING */
    printf("REQTYPE myString: %s\n", REQTYPE);

代码:

#include <stdio.h>      /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket() and bind() */
#include <arpa/inet.h>  /* for sockaddr_in and inet_ntoa() */
#include <stdlib.h>     /* for atoi() and exit() */
#include <string.h>     /* for memset() */
#include <unistd.h>     /* for close() */
#include <time.h>       /* Display time */

#define ECHOMAX 255     /* Longest string to echo */

void DieWithError(char *errorMessage);  /* External error handling function */
/* User Defined type */
typedef struct _ServerMessage{
    enum {New, Old, No_Message} messageType;    /* same size as an unsigned int */
    unsigned int SenderId;      /* unique client identifier */
    unsigned int RecipientId;       /* unique client identifier */
    char message[100];        /* text message */
} ServerMessage;       /* an unsigned int is 32 bits = 4 bytes */ 



int main(int argc, char *argv[])
{
    int sock;                        /* Socket */
    struct sockaddr_in echoServAddr; /* Local address */
    struct sockaddr_in echoClntAddr; /* Client address */
    unsigned int cliAddrLen;         /* Length of incoming message */
    char echoBuffer[ECHOMAX];        /* Buffer for echo string */
    unsigned short echoServPort;     /* Server port */
    int recvMsgSize;                 /* Size of received message */
    char *hldType;                   /* Parsing holding field */
    char *hldSend;                   /* Parsing holding field */
    char *hldRecip;                  /* Parsing holding field */
    char *hldMsg;                    /* Parsing holding field */
    char tmpType[1];                    /* Type of action requested by client,   where     0 is Send and 1 is Received */
    static const char *REQTYPE = "0";



    /* Test Struct */
    /*ServerMessage ServerMessage_new = {No_Message, 1234,5678,"Hello Server World -     No   Message"}; */
    ServerMessage ServerMessage_new[100];
    /* printf("Message Type: %d\n", ServerMessage_new.messageType);
    printf("Message SenderID: %04d\n", ServerMessage_new.SenderId);
    printf("Message RecipentID: %04d\n", ServerMessage_new.RecipientId);
    printf("Message Content: %s\n", ServerMessage_new.message); */

    if (argc != 2)         /* Test for correct number of parameters */
    {
        fprintf(stderr,"Usage:  %s <UDP SERVER PORT>\n", argv[0]);
        exit(1);
    }

    echoServPort = atoi(argv[1]);  /* First arg:  local port */

    /* Create socket for sending/receiving datagrams */
    if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
        DieWithError("socket() failed");

    /* Construct local address structure */
    memset(&echoServAddr, 0, sizeof(echoServAddr));   /* Zero out structure */
    echoServAddr.sin_family = AF_INET;                /* Internet address family */
    echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
    echoServAddr.sin_port = htons(echoServPort);      /* Local port */

    /* Bind to the local address */
    if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
        DieWithError("bind() failed");

    for (;;) /* Run forever */
    {
        /* Set the size of the in-out parameter */
        cliAddrLen = sizeof(echoClntAddr);

        /* Block until receive message from a client */
        if ((recvMsgSize = recvfrom(sock, echoBuffer, ECHOMAX, 0,
            (struct sockaddr *) &echoClntAddr, &cliAddrLen)) < 0)
            DieWithError("recvfrom() failed");

        printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr));

        /* Parse string from client */
        printf("echoBuffer Content: %s\n", echoBuffer);
        hldType = strtok(echoBuffer, ".");
        hldSend = strtok(NULL, "."); 
        hldRecip = strtok(NULL, "."); 
        hldMsg = strtok(NULL, ".");
        printf("value of hldType: %s\n", hldType);  /* Validated that it prints "0" */
        /* Store message sent from client */

        time_t now;
        time(&now);
        printf("%s", ctime(&now));

        if (strcmp(hldType,REQTYPE)  == 0)    /* NOT WORKING */
            printf("REQTYPE myString: %s\n", REQTYPE);

        ServerMessage_new[0].messageType = atoi(hldType);
        printf("hldType Content: %d\n", ServerMessage_new[0].messageType);
        ServerMessage_new[0].SenderId = atoi(hldSend);
        printf("hldSend Content: %04d\n", ServerMessage_new[0].SenderId);
        ServerMessage_new[0].RecipientId = atoi(hldRecip);
        printf("hldRecip Content: %04d\n", ServerMessage_new[0].RecipientId);       
        strncpy(ServerMessage_new[0].message, hldMsg, 40);
        printf("hldMsg Content: %s\n", ServerMessage_new[0].message);

        /* Send received datagram back to the client */
        if (sendto(sock, echoBuffer, recvMsgSize, 0, 
             (struct sockaddr *) &echoClntAddr, sizeof(echoClntAddr)) != recvMsgSize)
            DieWithError("sendto() sent a different number of bytes than expected");
    }
    /* NOT REACHED */
}

最佳答案

试试这个:

    printf( "comparing [%s] to [%s]\n", hldType, REQTYPE);
    if (strcmp(hldType,REQTYPE)  == 0)    /* NOT WORKING */
        printf("REQTYPE myString: %s\n", REQTYPE);

您可能会在其中一个字符串中发现多余的空格。您还可以打印调用 strcmp() 的返回值。

如果 hldTypeREQTYPE 都是 "0",那么 strcmp() 应该返回 0(等于)。

关于c - If 语句中使用的字符串指针不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13586336/

相关文章:

c - 如何找到程序的堆内存起始地址和结束地址?

c++ - 如何在不指定Unix 中所有C 编译器位置的情况下指定一个程序配置文件的位置?

c - 在 C 中为字符串数组实现快速排序 - 为什么我会收到 SIGABRT 错误?

c# - 以 ^Bo 开头的字符串

C++ 数组和指针

C 将字符串文字与返回字符指针的函数进行比较

pointers - Pascal 中的 nil 指针

考虑一下 C 函数的 "Data Type"吗?

c - 使用C程序从pendrive中删除所有文件

java - 字符串的计数频率