从字符串到unsigned char的转换错误

时间:2015-02-18 19:53:57

标签: c++ opencv

我正在开发opencv。我正在从文本文件中读取颜色值(格式为:123,32,123)。我需要将这些值插入vector(Vec3b)origColors。以下是我的代码。

ifstream myfile;
string line;
string delimiter = ",";
string temp;
vector<uchar> colors;
vector<Vec3b> origColors;
myfile.open("DedicatedColors.txt");
if (myfile.is_open())
{
    while ( getline (myfile,line) )
    {
        while(line.find(",",0) != string::npos)
        {
            size_t pos = line.find(",",0);
            temp = line.substr(0, pos);
            line.erase(0,pos+1);
            unsigned char* val=new unsigned char[temp.size() + 1]();
            copy(temp.begin(), temp.end(), val);
            colors.push_back(val); //Error Reference to type 'const value_type' (aka 'const unsigned char') could not bind to an lvalue of type 'unsigned char *'
        }
        dedColors.push_back(Vec3b(colors[0],colors[1],colors[2]));
        colors.clear();
    }
    myfile.close();
}

有人可以帮我解决这个问题吗?提前致谢。

2 个答案:

答案 0 :(得分:0)

“错误引用类型'const value_type'(又名'const unsigned char')无法绑定到'unsigned char *'类型的左值”

你有一个无符号字符向量,其push_back()方法只接受无符号字符,而你试图推回无符号字符指针。如果你真的需要使用unsigned char *并且不能只使用std::string,那么你的颜色矢量必须是std::vector<unsigned char*>

假设Vec3B只接受std::vector<unsigned char*>,我实际上倾向于使用std :: string直到最后,此时你可以调用std::string::c_str来获得一个空终止字符串。

像这样:

std::ifstream myfile("DedicatedColors.txt");

std::string line;

std::vector<Vec3b> origColors;

if (myfile.is_open())
{
    while (std::getline(myfile,line))
    {
        std::vector<std::string> colors;

        std::string::const_iterator last, itr;

        last = itr = line.begin();

        while (std::find(itr, line.end(), ',') != line.end())
        {
            colors.push_back(std::string(last, itr));

            last = itr++;
        }

        dedColors.push_back(Vec3b(colors[0].c_str(),colors[1].c_str(),colors[2].c_str()));
    }
}

编辑:我实际上只是注意到您可能正在尝试将RGB值转换为无符号字符,而不是像现在这样实际使用字符串。

然后,使用std::vector<unsigned char>代替std::vector<std::string>并使用std::stoi将您获得的RGB值从std::string转换为std::getline,然后像这样传递它们:

colors.push_back(std::stoi(std::string(last, itr)));

答案 1 :(得分:0)

正如已经指出的那样,您正在尝试将push_back unsigned char*加入到仅接受以下行unsigned char的向量中:

colors.push_back(val);

如果您有权访问boost库,则可以尝试以下代码(未测试):

 
#include <boost/lexical_cast.hpp>
// ... <your code> ...
while (getline(myfile, line)) {
    vector<string> colors;
    boost::split(line, colors, boost::is_any_of(','));
    dedColors.push_back(Vec3b(boost::lexical_cast<uchar>(colors[0]),
                              boost::lexical_cast<uchar>(colors[1]),
                              boost::lexical_cast<uchar>(colors[2])));
}
// ... <continue with your code> ...
相关问题