【问题标题】:c++ runtime error with concatenated message [closed]带有连接消息的c ++运行时错误[关闭]
【发布时间】:2016-03-18 21:18:28
【问题描述】:
我想在加载包含他的路径的位图时抛出错误
ALLEGRO_BITMAP* bitmap;
bitmap_path
if(bitmap=al_load_bitmap(bitmap_path)==0){
throw runtime_error("error loading bitmap from: '"<<bitmap_path<<"'");
};
//continue if no error
【问题讨论】:
标签:
c++
c++11
exception-handling
【解决方案1】:
您不能使用<< 运算符直接连接字符串。
如果bitmap_path 是std:::string,请改用+ 运算符:
throw runtime_error("error loading bitmap from: '" + bitmap_path + "'");
如果bitmap_path 是char*,则将其或第一个字符串文字转换为临时std::string,以便您可以使用+:
throw runtime_error("error loading bitmap from: '" + string(bitmap_path) + "'");
throw runtime_error(string("error loading bitmap from: '") + bitmap_path + "'");
否则,您可以使用std::ostringstream 或等效项来构造一个临时的std::string 值:
ostringstream oss;
oss << "error loading bitmap from: '" << bitmap_path << "'";
throw runtime_error(oss.str());