Jesse Good
Jesse Good

Reputation: 52365

std::strtoul equivalent in C++ standard library?

Consider the following example:

#include <iostream>
#include <clocale>
#include <cstdlib>
#include <string>
int main()
{
    std::setlocale(LC_ALL, "en_US.utf8");
    std::string s = "03A0";
    wchar_t wstr = std::strtoul(s.c_str(), nullptr, 16);
    std::wcout << wstr;
}

This outputs Π on Coliru.

Question

std::strtoul, is from <cstdlib>. I'm perfectly fine with using it, but I was wondering if the above example was possible using only the C++ standard library (perhaps stringstreams)?

Note also that there is no prefex 0x on the string indicating hexadecimal.

Upvotes: 3

Views: 2921

Answers (1)

Qaz
Qaz

Reputation: 61920

Sure, std::stoul:

wchar_t wstr = std::stoul(s, nullptr, 16);

The main difference is the fact that it can throw exceptions for errors.

Upvotes: 8

Related Questions