提问者:小点点

有人知道为什么在交换机内部使用stoi函数会返回恒定的错误吗?


我试图在开关中使用stoi函数,但它总是返回这个错误“[error]call to non-constexpr函数'intstd::stoi(const string&;,std::size_t*,int)'”我已经尝试了很多事情,我甚至尝试先将“pue”转换为const int并将变量放入其中,但它仍然返回同样类型的错误,说它不是常量表达式。 也许还有另外一种方式来写这个开关?

基本上,我使用一个条形码扫描器获得一个字符串,我想使用子字符串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;
}

共1个答案

匿名用户

除了其他人提出的建议之外,我还想补充这一点。

switch语句执行的检查是statice。 这意味着表达式在编译时必须是已知的。 因此,在使用switch case时,不能像使用stoi()函数那样添加任何动态表达式。