• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 553
  • Last Modified:

converting string to int

Hi Experts,

Is there a secure way of converting string to int.  I can use atoi( ) but, I am not sure if this is secure.
  • 2
1 Solution
Kent OlsenData Warehouse Architect / DBACommented:
Hi ambuli,

What do you mean by "secure"?

Converting a string to an integer is very straight-forward.  Several functions are available to do that, including atoi(), as you've mentioned.

evilrixSenior Software Engineer (Avast)Commented:
Sticking with native C, you could use strtol but it doesn't really offer any advantaged over atoi in terms of being more secure.

If you are using C++ you can use a ostringstream to perform the conversion.

// something like this...
std::string s = "1223";
std::ostringstream ss(s);
int i;
ss >> i;

If you're using Boost then you can use lexical_cast. This offers a very simple and safe way to cast between types.
evilrixSenior Software Engineer (Avast)Commented:
Incidentally, when you say secure I took that to mean a method that avoids the possibility of a buffer over-run in case the string isn't null terminated? If you are using C++ with std::string you should stick to using ostringstream or lexical_cast and that will not be an issue.
ambuliAuthor Commented:
Thank you.  Yes, I was concerned about overruns.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Build your data science skills into a career

Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now