473,406 Members | 2,404 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Converting a string to an integer

Hi,

I need a function which converts an string to an integer.
Currently I have this:

bool string2int(char* digit, int& result)
{
result = 0;

if (!(*digit >= '0' && *digit <='9'))
return false;
while (*digit >= '0' && *digit <='9')
{
result = (result * 10) + (*digit - '0');
digit++;
}

if (*digit != 0 && *digit != ',' && *digit != ']')
{
return false;
}

return true;
}

Has someone a better idea ?
Only ISO C++ please, no extra libs ;-)

Thanks...
Jul 22 '05 #1
6 2737
On 10 May 2004 20:18:25 GMT, Alex Neumann <no****@web.de> wrote:
Hi,

I need a function which converts an string to an integer.
Currently I have this:

bool string2int(char* digit, int& result)
{
result = 0;

if (!(*digit >= '0' && *digit <='9'))
return false;
while (*digit >= '0' && *digit <='9')
{
result = (result * 10) + (*digit - '0');
digit++;
}

if (*digit != 0 && *digit != ',' && *digit != ']')
{
return false;
}

return true;
}

Has someone a better idea ?
Only ISO C++ please, no extra libs ;-)


Well, you're doing things the hard way and not being as flexible as
facilities you already have in your libraries. If you want to code it by
hand, you could be using <cctype> facilities (e.g. isdigit), checking for
leading white space, etc. Note that C libs are also ISO C++, so my
suggestion to you would be to let the libs do all the heavy lifting:

#include <cstdio>
bool string2int(const char *intext, int &result)
{
return std::sscanf(intext, "%d", &result);
}

-leor

--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #2
On Mon, 10 May 2004 20:31:03 GMT in comp.lang.c++, Leor Zolman
<le**@bdsoft.com> wrote,
return std::sscanf(intext, "%d", &result);


While sscanf() certainly has a place, for converting a single number
why not omit the format business and call strtol() or atoi()?

Jul 22 '05 #3
Alex Neumann schrieb:
Hi,

I need a function which converts an string to an integer.
stdlib.h (cstdlib):

int atoi ( const char * string );

Convert string to integer.
Parses string interpreting its content as a number and returns an int
value.

Has someone a better idea ?
Only ISO C++ please, no extra libs ;-)
Found in cstdlib (of the GNU ISO C++ Library):
//
// ISO C++ 14882: 20.4.6 C library
//

Thanks...

Jul 22 '05 #4
In article <2g***********@uni-berlin.de>, Alex Neumann wrote:
Hi,

I need a function which converts an string to an integer.
Currently I have this:

bool string2int(char* digit, int& result)
{
result = 0;

if (!(*digit >= '0' && *digit <='9'))
return false; [-]
-1 and +1 are valid integers, but neither "-" nor "+" are
digits..
while (*digit >= '0' && *digit <='9')
{
result = (result * 10) + (*digit - '0'); [-]
1029384003948593093849 probably isn't a valid integer, yet
you don't catch overflows here.
[-] Has someone a better idea ?

[-]
http://www.google.com/ -- search for strtol.c and modify
the code to your needs.

Cheers,
Juergen

--
\ Real name : Juergen Heinzl \ no flames /
\ Email private : ju*****@manannan.org \ send money instead /
\ Photo gallery : www.manannan.org \ /
Jul 22 '05 #5

"marbac" <ma****@chello.at> wrote in message news:t8******************@news.chello.at...
int atoi ( const char * string );

Atoi has undefined behavior when fed certain inputs. The strtoX functions
are better behaved.

There's always stringstreams and boost's lexical cast as well.

string str("42");
instringstream is(str);
int i;
is >> i;

Jul 22 '05 #6
On Mon, 10 May 2004 21:04:53 GMT, David Harmon <so****@netcom.com> wrote:
On Mon, 10 May 2004 20:31:03 GMT in comp.lang.c++, Leor Zolman
<le**@bdsoft.com> wrote,
return std::sscanf(intext, "%d", &result);


While sscanf() certainly has a place, for converting a single number
why not omit the format business and call strtol() or atoi()?


Sure, those seem like more efficient choices in this case. I still like to
use sscanf because it is so flexible (if the types involved get changed,
there are more variations in format conversions than there are specialized
library functions for each type), and the savings in terms of time/space
seem like a drop in the bucket in the general scheme of things.

In this particular post, however, I was simply trying to convey the idea
of employing /some/ standard lib facility instead of hand-coding the
algorithm.
-leor

--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Cyde Weys | last post by:
I'm currently working on converting a simulator program from Visual Basic 6.0 to Visual C++ .NET. I've figured out most of the stuff, but there's still one thing I haven't gotten to and I've never...
7
by: RCS | last post by:
Okay, a rather 'interesting' situation has arisen at a place I work: I need to convert a database from Access to something that can be used over the web. I am currently maintaining and...
2
by: Asbjørn Ulsberg | last post by:
Hi. I'm trying to convert Brady Hegberg's great RTF2HTML VB 6.0 module to C#. I've managed to convert the VB code to VB.NET, which gave me the following code: Option Strict On Option...
0
by: Mark Allen | last post by:
Hello, I am creating an RTF document server side for a report. However I am having problems converting images into the required RTF format. I am converting the image into a string (binary)...
11
by: Steve | last post by:
I'm hoping someone can help me out. I'm a newbie to vb.net still. I'm trying to convert the code below from VB6 to VB.NET. I'm not sure of the best way to go. This is basically a simple...
4
by: sal | last post by:
Greets, All Converting array formula to work with datatables/dataset tia sal I finally completed a formula I was working on, see working code below. I would like to change this code so it...
13
by: Paraic Gallagher | last post by:
Hi, This is my first post to the list, I hope somebody can help me with this problem. Apologies if it has been posted before but I have been internet searching to no avail. What I am trying...
12
by: Rob Meade | last post by:
Hi all, Ok - I've come from a 1.1 background - and previously I've never had any problem with doing this: Response.Write (Session("MyDate").ToString("dd/MM/yyyy")) So, I might get this for...
9
by: Terry | last post by:
I am converting (attempting) some vb6 code that makes vast use of interfaces. One of the major uses is to be able to split out Read-only access to an obect. Let me give you a simple (contrived)...
2
by: Alex Buell | last post by:
Is there an elegant way of converting strings containing digits between different number bases in C++? I.e.: 10 (base 2) = 2 (base 10) FF (base 16) = 256 (base 10) F (base 16) = 1111 (base 2)...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.