Solved

converting string to int

Posted on 2012-03-31
4
532 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 45

Expert Comment

by:Kdo
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Little introduction about CP: CP is a command on linux that use to copy files and folder from one location to another location. Example usage of CP as follow: cp /myfoder /pathto/destination/folder/ cp abc.tar.gz /pathto/destination/folder/ab…
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é.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

776 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