【问题标题】:Result from my curl not read as string我的 curl 的结果未读为字符串
【发布时间】:2013-02-13 07:23:32
【问题描述】:

我正在为 POS 机编写此代码

我将来自网络链接的返回数据设置为“坏”,以便我可以测试它是否真的有效。 但是当我将结果与字符串“坏”进行比较时,它总是说它们不相等。 当我将结果打印到屏幕上时购买,它显示两个结果都不好。

我需要你的帮助。 代码如下

void checklogin(void) {
    CURL *curl;
    CURLcode res;
        long timeout = 30;
        char buffer[50000];
    //Initializing the CURL module
    curl = curl_easy_init();

    if(curl){
    //Tell libcurl the URL
    curl_easy_setopt(curl,CURLOPT_URL, "http://website.org/login.php");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "username=su&password=ch");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, myfunc);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); //tell curl to output its progress

           res = curl_easy_perform(curl);

           CTOS_LCDTClearDisplay();

           char mai[30];
           char mai2[30];

           char *serverresponse = "bad";
           sprintf(mai2, "%s" , serverresponse);
           sprintf(mai, "%s" , buffer);

           if(mai2 == mai){
            CTOS_LCDTPrint("Invalid username");
            CTOS_KBDGet(&key); 
           }else{
               //loginname = buffer;
               //mainusername = username;
               CTOS_LCDTPrintXY(1, 1, "Login Success");
               CTOS_LCDTPrintXY(1, 2, "Welcome");
               CTOS_KBDGet(&key);
               }


    }
}

【问题讨论】:

  • Google 比较 C 中的字符串。

标签: c string-comparison c-strings


【解决方案1】:

您所做的比较在 C++ 中有效,但是对于 C,您需要使用 strcmp() 来比较字符串。如果您作为参数提供的两个字符串包含相同的内容,则返回值将是 0。另外请记住,您可以在需要时使用其他strcmp() 函数,例如当您想要进行不区分大小写的比较时使用stricmp()

【讨论】:

    【解决方案2】:

    mai2 和 mai 是指向 char 数组的第一个字段的指针。由于这些是不同的数组,它们的地址当然是不同的。您想比较内容,因此您需要使用strcmp

    #include <string.h>
    strcmp("hello", "hello"); //0
    

    如果两个 char 数组包含相同的内容,则结果将为 0。

    if (strcmp(mai, mai2) == 0 ) {
        ...
    }
    

    -汉尼斯

    【讨论】:

    • 这应该是 string.h - 他似乎在使用 C,尽管将其标记为 C++。
    • 你说得对,立方。谢谢。编辑:string.h 是标准 C99,所以它应该用任何标准编译器编译。
    猜你喜欢
    • 2015-03-15
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2012-04-04
    • 2021-08-27
    • 2011-11-04
    • 1970-01-01
    相关资源
    最近更新 更多