C++ Converting string to unsigned int

I have the following string:

sThis = "2154910440";

unsigned int iStart=atoi(sThis.c_str());

However the result is

iStart = 2147483647

Does anybody see my mistake?

Answers


atoi converts a string to an int. On your system, an int is 32 bits, and its max value is 2147483647. The value you are trying to convert falls outside this range, so the return value of atoi is undefined. Your implementation, I guess, returns the max value of an int in this case.

You could instead use atoll, which returns a long long, which is guaranteed to be at least 64 bits. Or you could use a function from the stoi/stol/stoll family, or their unsigned counterparts, which will actually give useful error reports on out of range values (and invalid values) in the form of exceptions.

Personally, I like boost::lexical_cast. Even though it appears a bit cumbersome, it can be used in a more general context. You can use it in templates and just forward the type argument instead of having to have specializations


Need Your Help

Passing constructor parameters when resolving types in Unity: Best practice

c# .net dependency-injection unity-container

It's sometimes necessary when using dependency injection to provide the parameters to use in the constructor. This is something that's supported in Unity (and other dependency injection containers)...

Create a plugin to add my website functionalities on another website

javascript api plugins iframe oauth

I have a website A with a database and a search engine of some object, user can create account on my website then add comment for these objects.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.