Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

converting string to int

Posted on 2012-03-31
4
Medium Priority
?
551 Views
Last Modified: 2012-03-31
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.
0
Comment
Question by:ambuli
  • 2
4 Comments
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 37792057
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.


Kent
0
 
LVL 40

Accepted Solution

by:
evilrix earned 2000 total points
ID: 37792060
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.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 37792065
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.
0
 

Author Closing Comment

by:ambuli
ID: 37792077
Thank you.  Yes, I was concerned about overruns.
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I. Introduction There's an interesting discussion going on now in an Experts Exchange Group — Attachments with no extension (http://www.experts-exchange.com/discussions/210281/Attachments-with-no-extension.html). This reminded me of questions tha…
It’s 2016. Password authentication should be dead — or at least close to dying. But, unfortunately, it has not traversed Quagga stage yet. Using password authentication is like laundering hotel guest linens with a washboard — it’s Passé.
Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
Suggested Courses

886 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question