C++常用函数--stoi函数用法总结-创新互联

stoi函数

作用是将 n 进制的字符串转化为十进制,使用时包含头文件string.
定义如下:

创新互联主要从事成都网站建设、网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务洪泽,10年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792
int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );

参数:
str- 待转换的字符
pos- 其取值可以是一个空字符,在这种情况下,pos未被使用;另外如果pos不是空指针,函数将pos的值设置为str中数字后面的第一个字符的位置。
base- 字符中数字的进制,默认为10进制,如果base取值为0,则进制由字符串中的格式决定。

返回值:
如果转换成功的话,stoi函数将会把转换后的得到数字以int类型返回。
如果字符串中没有数字的话,将会抛出"invalid_argument"的异常;
如果字符串中的数字转换后超过int的范围,将会抛出"out_of_range"的异常;
因此使用stoi函数的时候最好加入异常处理。

例程如下:

#include#include#include#include#includeint main()
{const auto data = {"45",
        "+45",
        " -45",
        "3.14159",
        "31337 with words",
        "words and 2",
        "12345678901",
    };
 
    for (const std::string s : data)
    {std::size_t pos{};
        try
        {std::cout<< "std::stoi('"<< s<< "'): ";
            const int i {std::stoi(s, &pos)};
            std::cout<< i<< "; pos: "<< pos<< '\n';
        }
        catch(std::invalid_argument const& ex)
        {std::cout<< "std::invalid_argument::what(): "<< ex.what()<< '\n';
        }
        catch(std::out_of_range const& ex)
        {std::cout<< "std::out_of_range::what(): "<< ex.what()<< '\n';
            const long long ll {std::stoll(s, &pos)};
            std::cout<< "std::stoll('"<< s<< "'): "<< ll<< "; pos: "<< pos<< '\n';
        }
    }
 
    std::cout<< "\nCalling with different radixes:\n";
    for (const auto& [s, base]: {std::pair{"11",  2}, {"22",  3}, {"33",  4}, {"77",  8},
        {"99", 10}, {"FF", 16}, {"jJ", 20}, {"Zz", 36}, })
    {const int i {std::stoi(s, nullptr, base)};
        std::cout<< "std::stoi('"<< s<< "', "<< base<< "): "<< i<< '\n';
    }
}

输出为:

std::stoi('45'): 45; pos: 2
std::stoi('+45'): 45; pos: 3
std::stoi(' -45'): -45; pos: 4
std::stoi('3.14159'): 3; pos: 1
std::stoi('31337 with words'): 31337; pos: 5
std::stoi('words and 2'): std::invalid_argument::what(): stoi
std::stoi('12345678901'): std::out_of_range::what(): stoi
std::stoll('12345678901'): 12345678901; pos: 11
 
Calling with different radixes:
std::stoi('11', 2): 3
std::stoi('22', 3): 8
std::stoi('33', 4): 15
std::stoi('77', 8): 63
std::stoi('99', 10): 99
std::stoi('FF', 16): 255
std::stoi('jJ', 20): 399
std::stoi('Zz', 36): 1295
参考资料

std::stoi

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧

文章标题:C++常用函数--stoi函数用法总结-创新互联
浏览路径:https://www.cdcxhl.com/article38/coohsp.html

成都网站建设公司_创新互联,为您提供营销型网站建设网站设计公司软件开发动态网站网站收录自适应网站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

微信小程序开发