繁体   English   中英

C ++ std :: stoi异常:无效的参数

[英]C++ std::stoi Exception: Invalid Argument

我正在编写一个程序,可以从两个颜色十六进制代码计算平均颜色十六进制代码。 例如:我们向控制台输入了两个十六进制代码#15293E和#012549。

然后计算平均十六进制代码-#0B2743

所以,我的主要问题是当我使用std :: stoi函数将字符串从int转换为int时,它给我一个无效参数的异常。 这是我到目前为止编写的代码

#include "stdafx.h"
#include <stdexcept>
#include <iostream>
#include <string>

#define CONSOLE_LOG(x) std::cout << x
#define HEX_LEN 6
#define RGB_LEN 2

void enterHexCodes(std::string& hC1, std::string& hC2)
{
    bool isCorrectLen = false;
    do {
        std::cin >> hC1 >> hC2;
        if (hC1.length() != HEX_LEN + 1 || hC2.length() != HEX_LEN + 1)
        { 
            CONSOLE_LOG("ERROR!: Hex code should be no more than 7 symbols" << std::endl);
        } else { isCorrectLen = true; }
    } while (!isCorrectLen);
}

void getAvgHex(std::string& s, std::string& s1)
{
    int r, g, b,
        r1, g1, b1;

    std::string R = s.substr(1, RGB_LEN);
    std::string G = s.substr(3, RGB_LEN);
    std::string B = s.substr(5, RGB_LEN);

    std::string R1 = s1.substr(1, RGB_LEN);
    std::string G1 = s1.substr(3, RGB_LEN);
    std::string B1 = s1.substr(5, RGB_LEN);

    try {
        r = std::stoi(R), g = std::stoi(G), b = std::stoi(B);
        //std::stoi(R1), std::stoi(G1), std::stoi(B1);
    }
    catch (std::invalid_argument& e) {
        std::cout << "Invalid argument" << std::endl;
    }
    catch (std::out_of_range& e) {
        std::cout << "Out of range" << std::endl;
    }
    catch (...) {
        std::cout << "Something else" << std::endl;
    }

    std::cout << r << " " << g << " " << b;

}

int main()
{
    std::string hexCode1, hexCode2;

    enterHexCodes(hexCode1, hexCode2);

    getAvgHex(hexCode1, hexCode2);

    std::cin.get(); std::cin.get(); std::cin.get();
    return 0;
}

如何解决此异常,或者还有其他方法可以将字符串转换为int吗?

尝试添加十六进制的转换示例的基数:std :: stoi(str_hex,nullptr,16);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM