首页 文章

if(!buydat.empty())验证失败(始终为true)

提问于
浏览
0

我有一个'if validation',它总是正确的,即使我删除它正在接收的入站数据以确保它是空的,我仍然会在不应该的时候到达我的cout语句 .

码:

void buymngr(){
        vector<std::string> buydat;
        vector<std::string> markdat;
        vector<std::string> pricedat;
        buydat = getmyData();
        if(!buydat.empty()){

                cout << "You 'do' have buy string match data!" << endl;
        }

它调用函数getmyData,它负责获取数据

getmyData:

vector<string> getmyData()
{
        FILE *mydfp = popen("php getMyorders.php", "r");
        if (mydfp == NULL) perror ("Error opening file");
        char mydbuff[BUFSIZ];
        vector<string> vrecords;
        while(fgets(mydbuff, sizeof(mydbuff), mydfp) != NULL){
                size_t n = strlen(mydbuff);
                //clean '\0' from fgets
                if (n && mydbuff[n - 1] == '\n') mydbuff[n - 1] = '\0';
                if (mydbuff[0] != '\0') vrecords.push_back(mydbuff);
        }
        cout << "I got my own data" << endl;
        return vrecords;
}

当代码合法地为'true'时,它运行正常并且正常执行所有功能 . 但是当做错时,它仍然验证为真,然后分段错误(gdb没有指向特定的行,但错误确实似乎是试图处理真正不存在的有效数据) .

2 回答

  • 0

    您的 if 语句会检查 b < buydat.size() . 您可以使用以下语句在向量的末尾进行索引:

    if ( buydat[b] == "Buy" ){
        pricedat.push_back(buydat[b+1]);
    }
    

    编辑:"You could index..."的意思是"You could BE INDEXING..." .
    这是一个观察,而不是一个建议:您正在向 pricedat 向量添加 buydat[b+1] . 如果在您的测试中 (b == (buydat.size()-1)) ,您将 push_back(buydat[buydat.size()] - 无效 . 您发布的代码没有任何测试,以确保 buydat.size() 小于 b+N (无论 N 是什么 - 我根据您的 for 循环猜测7)

  • 0

    评论太久了,所以跟进答案:然后你的问题出现在 getMyData() . 考虑:

    #include <vector>
    #include <string>
    std::vector<std::string> getmyData()
    {
        std::vector<std::string> vrecords;
        vrecords.push_back("anything.");
        vrecords.push_back("anything 2.");
        // push some more data here so the result -looks- like
        // whatever you expect the output of your PHP to be.
    
        // also, your original version of this function never closes mydfp
    
        return vrecords;
    }
    
    void buymngr(){
        std::vector<std::string> buydat;
        std::vector<std::string> markdat;
        std::vector<std::string> pricedat;
        buydat = getmyData();
        if(!buydat.empty()){
            std::cout << "You 'do' have buy string match data!" << std::endl;
        }
    }
    
    int main()
    {
        buymngr();
        return 0;
    }
    

    检查 getMyorders.php 的输出 - 如果输出错误,那么,你的问题就出现了 . 如果没有,请发布 getMyOrders.php 的输出 .

相关问题