Skip to content
Fix Code Error

How can I convert a std::string to int?

March 13, 2021 by Code Error
Posted By: Anonymous

Just have a quick question. I’ve looked around the internet quite a bit and I’ve found a few solutions but none of them have worked yet. Looking at converting a string to an int and I don’t mean ASCII codes.

For a quick run-down, we are passed in an equation as a string. We are to break it down, format it correctly and solve the linear equations. Now, in saying that, I’m not able to convert a string to an int.

I know that the string will be in either the format (-5) or (25) etc. so it’s definitely an int. But how do we extract that from a string?

One way I was thinking is running a for/while loop through the string, check for a digit, extract all the digits after that and then look to see if there was a leading ‘-‘, if there is, multiply the int by -1.

It seems a bit over complicated for such a small problem though. Any ideas?

Solution

In C++11 there are some nice new convert functions from std::string to a number type.

So instead of

atoi( str.c_str() )

you can use

std::stoi( str )

where str is your number as std::string.

There are version for all flavours of numbers:
long stol(string), float stof(string), double stod(string),…
see http://en.cppreference.com/w/cpp/string/basic_string/stol

Answered By: Anonymous

Related Articles

  • What are the new features in C++17?
  • no match for ‘operator
  • Getting weird compilation error in defining a std::set with…
  • I do not use TBB, but I get linker errors related to TBB
  • What is the worst programming language you ever worked with?
  • Callback functions in C++
  • Baffling variadic templates exercise
  • Error with C++20 ranges and std::views::take
  • How to write a large buffer into a binary file in C++, fast?
  • unique_ptr is not deleted after calling reset

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Open link in new tab or window

Next Post:

PHP equivalent of .NET/Java’s toString()

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error