You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++生成十六进制颜色BMP图报错:无法基于用户输入保存文件

问题修复方案

你的代码存在3个核心问题导致测试不通过:

  • 绘图逻辑完全未生效:main函数内的bool DrawRectangle(...)是函数声明语句,并非调用图片对象的绘图方法,创建的100*100画布始终为空白,没有填充指定颜色
  • 缺乏输入合法性校验:未判断用户输入的十六进制色值长度是否为6位,也没有处理用户输入带#前缀的常见场景,且HexToInteger返回-1的异常情况未捕获,会传入非法参数生成错误内容
  • 文件名逻辑不匹配:控制台输出的文件名为xxx.bmp,但调用SaveImageBmp时直接传入原始色值,若接口不会自动补后缀则生成的文件无.bmp后缀,导致测试用例无法识别输出文件
修正后完整代码
#include <stdlib.h>

#include <iostream>
#include <string>

#include "cpputils/graphics/image.h"

int HexToInteger(std::string hex) {
  // Only works on strings length 2.
  if (hex.size() != 2) {
    return -1;
  }
  // Convert hex string, base 16 string, to integer.
  const int kBaseSixteen = 16;
  return strtoul(hex.c_str(), nullptr, kBaseSixteen);
}

int main() {
  std::cout << "Enter a hex code: ";
  std::string hex_color;
  std::cin >> hex_color; 

  // 处理#前缀
  if (hex_color[0] == '#') {
    hex_color = hex_color.substr(1);
  }
  // 校验色值长度
  if (hex_color.size() != 6) {
    std::cout << "Invalid hex color code, please input 6-digit hex value." << std::endl;
    return 1;
  }

  // Convert input string to three integers
  std::string red = hex_color.substr(0, 2); 
  std::string green = hex_color.substr(2, 2);
  std::string blue = hex_color.substr(4, 2);
 
  // Create graphic::Color object 
  int RedasInt = HexToInteger(red); 
  int GreenasInt = HexToInteger(green);
  int BlueasInt = HexToInteger(blue); 
  // 校验转换结果合法性
  if (RedasInt < 0 || GreenasInt <0 || BlueasInt <0) {
    std::cout << "Invalid hex character detected." << std::endl;
    return 1;
  }
  graphics::Color color(RedasInt, GreenasInt, BlueasInt);

  // Draw and save image
  graphics::Image image(100, 100);
  // 实际调用成员方法填充全图颜色
  image.DrawRectangle(0, 0, 100, 100, color);
  // 保存时补全.bmp后缀
  std::string file_name = hex_color + ".bmp";
  image.SaveImageBmp(file_name);
  // Output
  std::cout << "Color swatch saved to " << file_name; 
  return 0;
}

内容的提问来源于stack exchange,提问作者hello

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:09:04