Solved

converting string to int

Posted on 2012-03-31
4
536 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 45

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 500 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
Fine Tune your automatic Updates for Ubuntu / Debian
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
Suggested Courses

738 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