Solved

converting string to int

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Join Greg Farro and Ethan Banks from Packet Pushers (http://packetpushers.net/podcast/podcasts/pq-show-93-smart-network-monitoring-paessler-sponsored/) and Greg Ross from Paessler (https://www.paessler.com/prtg) for a discussion about smart network …
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
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.

708 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now