我正在从文件中读取数据(名称颜色),并将其插入表中,当匹配名称时,将返回正确的颜色。
如何在函数中返回一个字符串
class call_color
{
public:
std::map<std::string, std::string> table;
bool read(std::string &fname)
{
std::ifstream ifs (fname, std::ifstream::in);
if(ifs.fail())
{
printf("Cant open\n");
return false;
}
return read(ifs);
}
bool read(std::istream &is)
{
for (std::string line; std::getline(is, line);)
{
char *name = strtok(const_cast<char*>(line.c_str()), " \r");
if(name != nullptr)
{
char *color = strtok(nullptr, " ");
if(color != nullptr)
{
table[name] = color;
}
else
{
printf("No color %s\n", line.c_str());
return false;
}
}
else
{
printf("No Name\n");
return false;
}
}
return true;
}
std::string get_color(std::string name)
{
std::string color;
std::map<std::string, std::string>::iterator it;
it = table.find(name);
if (it != table.end())
{
color = it->second;
}
return color;
}
};
它返回一个巨大的负值(-772802864)或任何名称的巨大正值。但我希望得到一个字符串:scdscsdcs
答案 0 :(得分:1)
如果你想返回一个空字符串,你应该添加
return std::string();
在功能结束时。
另请注意,您的else子句包含错误的返回类型。 0无法转换为有效的std :: string。
答案 1 :(得分:0)
这可能有所帮助。
std::string get_color(std::string name)
{
std::string color;
std::map<std::string, std::string>::iterator it;
it = table.find(name);
if (it != table.end())
{
color = it->second;
}
else if (name == "Terminate")
{
color = '';
}
return color;
}
答案 2 :(得分:0)
有问题
table[name] = color;
map table
期望std :: string对象既是键又是值,但name
和color
都是char *。你应该这样做:
table[str(name)] = str(color);