在popen调用中丢失数据

时间:2014-11-26 08:15:20

标签: c++ popen

我的程序编译没有错误,似乎正确地运行了所有步骤。它应该进行php调用并返回数据。 tcpdump确实显示请求已经发出,因此popen正在执行,但接收方永远不会更新。 我能找到的唯一差异是命令变量似乎缺少数据。

#.trol.o

market max price is 0.00638671 at position 0
php coin.php 155 0.006387
0.00638672

输出中的第二行是我发送给popen的命令

cout << command << endl; ->  php coin.php 155 0.006387

该数字应该与它下面的数字相同0.00638672 数字6和数字2已被切断。

如何将正确的数据输入我的popen命令?

代码:

void mngr(){
        //vector defs
        vector<std::string> buydat;
        vector<std::string> markdat;
        vector<std::string> pricedat;
        vector<std::string> purchaseid;
        vector<double> doublePdat;
        vector<double> doubleMdat;
        doublePdat.reserve(pricedat.size());
        doubleMdat.reserve(markdat.size());
        char buybuff[BUFSIZ];
        char command[70];
        char sendbuy[12];
        buydat = getmyData();
        markdat = getmarketbuyData();
        //string match "Buy" and send results to new vector with pricedat.push_back()
        for(int b = 2; b < buydat.size(); b+=7){
                if ( buydat[b] == "Buy" ) {
                         pricedat.push_back(buydat[b+1]);
                }
        }
        transform(pricedat.begin(), pricedat.end(), back_inserter(doublePdat), [](string const& val) {return stod(val);});
        transform(markdat.begin(), markdat.end(), back_inserter(doubleMdat), [](string const& val) {return stod(val);});
        auto biggestMy = std::max_element(std::begin(doublePdat), std::end(doublePdat));
        std::cout << "my max price is " << *biggestMy << " at position " << std::distance(std::begin(doublePdat), biggestMy) << std::endl;
        auto biggestMark = std::max_element(std::begin(doubleMdat), std::end(doubleMdat));
        std::cout << "market max price is " << *biggestMark << " at position " << std::distance(std::begin(doubleMdat), biggestMark) << std::endl;
        if (biggestMy > biggestMark){
                cout << "Biggest is Mine!" << endl;
        }
        else if (biggestMy < biggestMark){
                //cout << "Biggest is market!";
                *biggestMark += 0.00000001;
                sprintf(sendbuy,"%f",*biggestMark);
                sprintf(command, "php coin.php 155 %s",sendbuy);
                FILE *markbuy = popen(command, "r");
                if (markbuy == NULL) perror ("Error opening file");
                while(fgets(buybuff, sizeof(buybuff), markbuy) != NULL){
                        size_t h = strlen(buybuff);
                        //clean '\0' from fgets
                        if (h && buybuff[h - 1] == '\n') buybuff[h - 1] = '\0';
                        if (buybuff[0] != '\0') purchaseid.push_back(buybuff);
                }

                cout << command << endl;
                cout << *biggestMark << endl;

        }
}

1 个答案:

答案 0 :(得分:1)

我会尝试使用long float格式而不是float,因为maximumMark的类型应该被计算为双精度迭代器。我的意思是尝试将sprintf(sendbuy,"%f",*biggestMark);更改为sprintf(sendbuy,"%lf",*biggestMark);。希望这会有所帮助。