首页 > 解决方案 > 有谁知道为什么在开关内使用 stoi 函数会返回不断的错误?

问题描述

我正在尝试在开关内使用 stoi 函数,但它一直给我返回此错误“[Error] call to non-constexpr function 'int std::stoi(const string&, std::size_t*, int)'”我尝试了多种方法,我什至尝试先将“PUE”转换为 const int 并将变量放在那里,但它仍然给我返回相同类型的错误,说它不是常量表达式。也许还有另一种写这个开关的方法?

基本上我正在使用条形码扫描仪来获取字符串,并且我想使用 substr A 与一些预定义数据进行比较并将其显示在屏幕上。

谢谢。

 #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

main()
{
string A, B1, B2, C;
string scan;
    cout << "Esperando a scan...";
        
    cin >> scan;
    cout << "Codigo:" << scan;
    
    A = scan.substr (0,3); 
    B1 = scan.substr (4,3); 
    B2 = scan.substr (5,7); 
    C = scan.substr (13,4); 
    
    //comparing

    switch(stoi(A))
    case stoi("PUE",nullptr,0):
        A << "PUERTA";
    case stoi("PAN"):
        A << "PANEL";
    case stoi("LAC"):
        A << "LACADO";
    
    cout << "\n Producto:" << A << "\n Acabado:" << B1 << "\n Color:" << B2 << "\n Nº Pedido:" << C;
}

标签: c++stringtype-conversionswitch-statementcompare

解决方案


改变:

 switch(stoi(A))
    case stoi("PUE",nullptr,0):
        A << "PUERTA";
    case stoi("PAN"):
        A << "PANEL";
    case stoi("LAC"):
        A << "LACADO";

至:

 switch((A))
    case "PUE":
        A << "PUERTA";
    case "PAN":
        A << "PANEL";
    case "LAC":
        A << "LACADO";

我不知道您为什么要将字符串转换为 int,您提供的代码中根本不需要它....


推荐阅读