【问题标题】:return char from std::string vector从 std::string 向量返回 char
【发布时间】:2014-11-23 05:28:18
【问题描述】:

你如何传递 popen 数据? 我有一个我使用的脚本,但是当我尝试将数据带入另一个函数时,我得到一个转换错误 -> 不推荐从字符串常量到 'char*' 的转换,因为 popen 想要使用标准字符。

代码:

#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>

using namespace std;

FILE *init( char *fname ){
        FILE *fp = popen( fname, "r" );
        return fp;
}

char getmarketbuyData(FILE *fp){
        char buff[BUFSIZ];
        vector<std::string> vrecords;
        while(std::fgets(buff, sizeof buff, fp) != NULL){
                size_t n = std::strlen( buff );
                if ( n && buff[n-1] == '\n' ) buff[n-1] = '\0';
                if ( buff[0] != '\0' ) vrecords.push_back( buff );
        }
        for(int t = 0; t < vrecords.size(); ++t){
                cout << vrecords[t] << " " << endl;
        }
                return 0;
}

int main(void){
        FILE *fp = NULL;
        fp = init("/usr/bin/php getMyorders.php 155");
        if (fp == NULL) perror ("Error opening file");
        if ( fp )
                getmarketbuyData( fp );
}

错误:

# g++ -g returnFileP.cpp -o returnFileP.o -std=gnu++11 returnFileP.cpp:在函数'int main()'中: returnFileP.cpp:29:66: 警告:不推荐将字符串常量转换为 'char*' [-Wwrite-strings]

如何正确地将 popen 数据传递/返回给另一个函数?

【问题讨论】:

  • 如果您不修改fname,则改为const。不要强迫该函数的用户解决您缺乏 const 正确性的问题。

标签: c++ string c++11 popen


【解决方案1】:

main 中调用init 时出现错误。字符串文字"/usr/bin/php getMyorders.php 155" 的类型为const char *,调用init 需要隐式转换为char *。这种转换(对于字符串文字)是允许的,但现在已弃用。

popen 的第一个参数的类型为const char *,所以我看不出init 需要非常量参数的原因。声明为

FILE *init( const char *fname )

摆脱警告。

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    相关资源
    最近更新 更多