13

Since c++11 the <string> header provides :

To convert from std::string to signed integers.

We also have their unsigned counterpart :

Now, even a child would notice something is missing right ? :)

So the question is: is there a reason not to provide an std::stoui or is it just something that was forgotten (And basically how could something this "obvious" be forgotten)?

Also, does that mean that the correct way of converting an std::string to unsigned int is :

unsigned int ui = static_cast<unsigned int>(std::stoul(std::string{"42"}));
Drax
  • 12,682
  • 7
  • 45
  • 85
  • Although none of *those* answers seem particularly satisfying to a sense of symmetry... – Brett Hale Jan 21 '14 at 10:08
  • "how could something this "obvious" be forgotten" -- if it was an oversight (and I'm not saying it was) that would be surprising but not unprecedented. `copy_if` was missing from C++03. I've heard it said that was more or less due to a copy-paste error. – Steve Jessop Jan 21 '14 at 10:10
  • @BrettHale The main part of the question might be a duplicate of the first one, but i'm also realy intersted in "what is the best way to do the conversion" which is the second part of the question, or should i open another question for that ? – Drax Jan 21 '14 at 10:12
  • The answer to the second part of the question is "no", because it doesn't do a range check :-) – Steve Jessop Jan 21 '14 at 10:13
  • @SteveJessop so how to ? :) – Drax Jan 21 '14 at 10:13
  • @Drax There is a good way to do the conversion shown in Mike Seymour's answer to the other question. – interjay Jan 21 '14 at 10:17
  • `unsigned int stoui(const string &str, size_t *idx = 0, int base = 10) { unsigned long u = stoul(str, idx, base); if (u > UINT_MAX) throw out_of_range(str); return u; }` – Steve Jessop Jan 21 '14 at 10:19
  • @SteveJessop Why does it work without a cast ? – Drax Jan 21 '14 at 10:23
  • @Drax `unsigned long` is implicitly convertible to `unsigned int`. – Simple Jan 21 '14 at 10:24
  • @Simple Since when ? O_o Can you point to some source for this plz, even an SO question ? – Drax Jan 21 '14 at 10:28
  • @Drax http://en.cppreference.com/w/cpp/language/implicit_cast :) – Drax Jan 21 '14 at 10:42
  • @Drax: since always. You might have to add the cast to silence a compiler warning for an implicit narrowing conversion. That depends on your compiler and options, but narrowing clearly is "safe" because of the range check. – Steve Jessop Jan 21 '14 at 10:51

0 Answers0