473,386 Members | 1,720 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,386 software developers and data experts.

atoi()

What is the preferred C++ alternative to C's atoi(), if there is one?

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Jul 22 '05 #1
16 4807
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in
message news:bu**********@chessie.cirr.com...
What is the preferred C++ alternative to C's atoi(), if there is one?
--
Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.


The standard alternative is to construct a stringstream and read its
data into an int using >>. See also
http://www.boost.org/libs/conversion/lexical_cast.htm.

Jonathan
Jul 22 '05 #2
Jonathan Turkanis <te******@kangaroologic.com> spoke thus:
The standard alternative is to construct a stringstream and read its
data into an int using >>.


You would recommend such an approach in the following situation?

#include <cstdlib>

int main( int argc, char *argv[] )
{
int count=0;
if( argc > 1 ) {
count=atoi( argv[1] ); // <- worth setting up a stringstream?
}
return EXIT_SUCCESS;
}

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Jul 22 '05 #3
Christopher Benson-Manica wrote:
Jonathan Turkanis <te******@kangaroologic.com> spoke thus:

The standard alternative is to construct a stringstream and read its
data into an int using >>.

You would recommend such an approach in the following situation?

#include <cstdlib>

int main( int argc, char *argv[] )
{
int count=0;
if( argc > 1 ) {
count=atoi( argv[1] ); // <- worth setting up a stringstream?


You forgot std::.
}
return EXIT_SUCCESS;
}


Well, atoi() doesn't allow much in the way of error detection &
recovery. It silently invokes undefined behavior on overflow, if I
recall correctly. I'd recommend using either the stringstream method or
possibly strtol() or a related function - whichever you think is
appropriate for the situation.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #4
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in
message news:bu**********@chessie.cirr.com...
Jonathan Turkanis <te******@kangaroologic.com> spoke thus:
The standard alternative is to construct a stringstream and read its data into an int using >>.


You would recommend such an approach in the following situation?

#include <cstdlib>

int main( int argc, char *argv[] )
{
int count=0;
if( argc > 1 ) {
count=atoi( argv[1] ); // <- worth setting up a stringstream?
}
return EXIT_SUCCESS;
}


int main( int argc, char *argv[] )
{
int count=0;
if( argc > 1 && (std::stringstream(argv[1]) >> count) )
/* ... */
}
return EXIT_SUCCESS;
}

There is a certain overhead to using a stringstream or stringbuf:
constuction of a locale, and depending on the implementation,
initialization of a number of member pointers and possibly a
synchronization construct. So its not appropriate always. It is,
however, the 'standard C++ alternative.'

Jonathan

Jul 22 '05 #5

"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in message news:bu**********@chessie.cirr.com...
What is the preferred C++ alternative to C's atoi(), if there is one?

I won't even use atoi in C. There are input conditions that cause it to
invoke undefined behavior. strtol is much better behaved.

Jul 22 '05 #6
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> schrieb im
Newsbeitrag news:bu**********@chessie.cirr.com...
Jonathan Turkanis <te******@kangaroologic.com> spoke thus:

#include <cstdlib>

int main( int argc, char *argv[] )
{
int count=0;
if( argc > 1 ) {
count=atoi( argv[1] ); // <- worth setting up a stringstream?
}
return EXIT_SUCCESS;
}


What is the difference?

#include <boost/lexical_cast.hpp> // #include <cstdlib>

int main( int argc, char *argv[] )
{
int count=0;
if( argc > 1 ) {
count = boost::lexical_cast<int>(argv[1]); // count=atoi( argv[1] );
}
// return EXIT_SUCCESS;
}

Why should one _not_ use lexical_cast in this/any case? Ok, to
have the same result here you had to surround the cast by a try
block, catching the appropriate boost::bad_lexical_cast but...

In my opinion, lexical_cast is to be preferred in _any_ realistical
case. In not realistical cases, noone cares.

Bye

Norbert

Jul 22 '05 #7
"Norbert Riedlin" <no*************@t-online.de> wrote in message
news:bu*************@news.t-online.com...
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> schrieb im
Newsbeitrag news:bu**********@chessie.cirr.com...
Jonathan Turkanis <te******@kangaroologic.com> spoke thus:

#include <cstdlib>

int main( int argc, char *argv[] )
{
int count=0;
if( argc > 1 ) {
count=atoi( argv[1] ); // <- worth setting up a stringstream?
}
return EXIT_SUCCESS;
}

What is the difference?

#include <boost/lexical_cast.hpp> // #include <cstdlib>

int main( int argc, char *argv[] )
{
int count=0;
if( argc > 1 ) {
count = boost::lexical_cast<int>(argv[1]); // count=atoi(

argv[1] ); }
// return EXIT_SUCCESS;
}

Why should one _not_ use lexical_cast in this/any case? Ok, to
have the same result here you had to surround the cast by a try
block, catching the appropriate boost::bad_lexical_cast but...

In my opinion, lexical_cast is to be preferred in _any_ realistical
case. In not realistical cases, noone cares.


Do we disagree on anything? I mentioned the 'standard C++ alternative'
as well as boost::lexical cast; I did not express any preference.

Jonathan
Jul 22 '05 #8

"Jonathan Turkanis" <te******@kangaroologic.com> schrieb im Newsbeitrag
news:bu************@ID-216073.news.uni-berlin.de...
"Norbert Riedlin" <no*************@t-online.de> wrote in message
news:bu*************@news.t-online.com...
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> schrieb im
Newsbeitrag news:bu**********@chessie.cirr.com...

Do we disagree on anything? I mentioned the 'standard C++ alternative'
as well as boost::lexical cast; I did not express any preference.

Jonathan

Not at all. If you look closer, I was relying to Christopher's post. I
should have
been more careful cutting the posting though...

Bye

Norbert
Jul 22 '05 #9

"Norbert Riedlin" <no*************@t-online.de> skrev i en meddelelse
news:bu*************@news.t-online.com...
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> schrieb im
Newsbeitrag news:bu**********@chessie.cirr.com...
Jonathan Turkanis <te******@kangaroologic.com> spoke thus:

#include <cstdlib>

int main( int argc, char *argv[] )
{
int count=0;
if( argc > 1 ) {
count=atoi( argv[1] ); // <- worth setting up a stringstream?
}
return EXIT_SUCCESS;
}


What is the difference?

#include <boost/lexical_cast.hpp> // #include <cstdlib>

int main( int argc, char *argv[] )
{
int count=0;
if( argc > 1 ) {
count = boost::lexical_cast<int>(argv[1]); // count=atoi( argv[1] );
}
// return EXIT_SUCCESS;
}

Why should one _not_ use lexical_cast in this/any case? Ok, to
have the same result here you had to surround the cast by a try
block, catching the appropriate boost::bad_lexical_cast but...

In my opinion, lexical_cast is to be preferred in _any_ realistical
case. In not realistical cases, noone cares.

Bye

Norbert


While I would agree with you in the general case, there could be cases where
avoiding streams would better be avoided. One example is when you write a
program where you are concerned about its footprint: if that program only
uses streams this one place, it does justify using an alternative approach.

Kind regards
Peter
Jul 22 '05 #10

"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in message
news:bu**********@chessie.cirr.com...
What is the preferred C++ alternative to C's atoi(), if there is one?

- std::atoi is standard C++
- std::strtol is also standard C and standard C++ and is superior in every
respect ( IMHO atoi should be deprecated ).
- You could use an istrstream but why bother?
- I can think of no good reason to use an istringstream if you have a char*.

- as far as I am aware there is no stream equivalent of the strtol ability
to read numbers in decimal,octal or hex

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.

Jul 22 '05 #11
Christopher Benson-Manica wrote:
What is the preferred C++ alternative to C's atoi(), if there is one?


I rolled my own alternative. The idea is this, but if you're looking
for an improvement over atoi, you might consider validating the pointer,
the base, and the digits.
template< typename N > // unsigned numeric type
N ato( char const* p, unsigned base =10 )
{
N result = N( );

while( *p )
{
result = result * base + ( *p <= '9' ? *p - '0' : *p - 'a' + 10 );
++p;
}

return result;
}

#include <iostream>

int main( int argc, char *argv[] )
{
if( argc > 1 )
{
unsigned base = 10;

if( argc > 2 )
{
base = ato< unsigned >( argv[ 2 ] );
}

std::cout << ato< int >( argv[ 1 ], base ) << '\n';
}
}

Jul 22 '05 #12

"Nick Hounsome" <nh***@blueyonder.co.uk> wrote in message news:zT****************@news-binary.blueyonder.co.uk...
- std::strtol is also standard C and standard C++ and is superior in every
respect ( IMHO atoi should be deprecated ).


In my opinion, it could just be fixed by requiring it to be defined as:
int atoi(const char* s) { return strtol(s, 0, 10); }

That is, change it from undefined behavior to implementation defined value on
overflow. C99 even includes the above snippet as the definition "except for error
behavior."

Jul 22 '05 #13

"Jeff Schwab" <je******@comcast.net> schrieb im Newsbeitrag
news:o5********************@comcast.com...
template< typename N > // unsigned numeric type
N ato( char const* p, unsigned base =10 )
{
N result = N( );

while( *p )
{
result = result * base + ( *p <= '9' ? *p - '0' : *p - 'a' + 10 );
++p;
}

return result;
}

You are asuming the ASCII character set? In EBCDIC '9' > 'a'.

Bye

Norbert
Jul 22 '05 #14
Norbert Riedlin wrote:
"Jeff Schwab" <je******@comcast.net> schrieb im Newsbeitrag
news:o5********************@comcast.com...
template< typename N > // unsigned numeric type
N ato( char const* p, unsigned base =10 )
{
N result = N( );

while( *p )
{
result = result * base + ( *p <= '9' ? *p - '0' : *p - 'a' + 10 );
++p;
}

return result;
}


You are asuming the ASCII character set? In EBCDIC '9' > 'a'.

Bye

Norbert

No assumption, just a mistake. That should have said:

'0' <= *p && *p <= '9'

Jul 22 '05 #15
"Jeff Schwab" <je******@comcast.net> schrieb im Newsbeitrag
news:f-********************@comcast.com...
Norbert Riedlin wrote:
"Jeff Schwab" <je******@comcast.net> schrieb im Newsbeitrag
news:o5********************@comcast.com...
template< typename N > // unsigned numeric type
N ato( char const* p, unsigned base =10 )
{
N result = N( );

while( *p )
{
result = result * base + ( *p <= '9' ? *p - '0' : *p - 'a' + 10 );
++p;
}

return result;
}


You are asuming the ASCII character set? In EBCDIC '9' > 'a'.


No assumption, just a mistake. That should have said:

'0' <= *p && *p <= '9'

Ok, so you are asuming correct and all lowercase input?

Bye Norbert

Jul 22 '05 #16
Norbert Riedlin wrote:
"Jeff Schwab" <je******@comcast.net> schrieb im Newsbeitrag
news:f-********************@comcast.com...
Norbert Riedlin wrote:
"Jeff Schwab" <je******@comcast.net> schrieb im Newsbeitrag
news:o5********************@comcast.com...
template< typename N > // unsigned numeric type
N ato( char const* p, unsigned base =10 )
{
N result = N( );

while( *p )
{
result = result * base + ( *p <= '9' ? *p - '0' : *p - 'a' + 10 );
++p;
}

return result;
}
You are asuming the ASCII character set? In EBCDIC '9' > 'a'.


No assumption, just a mistake. That should have said:

'0' <= *p && *p <= '9'


Ok, so you are asuming correct and all lowercase input?

Bye Norbert


Are you unable to read? Here's the part of my post you snipped.

"The idea is this, but if you're looking for an improvement over atoi,
you might consider validating the pointer, the base, and the digits."

Jul 22 '05 #17

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

Similar topics

19
by: Mike Moum | last post by:
I think there may be a bug in string.atoi and string.atol. Here's some output from idle. > Python 2.3.4 (#2, Jan 5 2005, 08:24:51) > on linux2 > Type "copyright", "credits" or "license()"...
6
by: John Smith | last post by:
What's wrong with the use of atoi in the following code? Why do I get the error message: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *' char cBuffer; void...
5
by: Bansidhar | last post by:
atoi() function seems not to have any support for Hex, octal number. Usually when I read from a text file then it contain number like 0x232 etc. In this case atoi() fells. In case of itoa() there...
15
by: puzzlecracker | last post by:
does anyone know how to implement this function efficiently?
47
by: sudharsan | last post by:
Hi could you please explain wat atoi( ) function is for and an example how to use it?
13
by: ptq2238 | last post by:
Hi, I have written this code to help me learn C but I'm not sure why gcc - Wall is giving me an error when I compile Basically I want to read in a character then a number and then manipulate...
9
by: Would | last post by:
Hey, hopefully one of you can help me... I keep getting an unresolved external 'atoi(char)' and I dont know why.. here is the code #include <iostream> #include <stdlib.h> using namespace std; ...
11
by: Nezhate | last post by:
Hi all, Can you help me? Why this warning appears in the next simple code ? warning: passing argument 1 of ‘atoi’ makes pointer from integer without a cast. #include <stdio.h> #include...
50
by: Bill Cunningham | last post by:
I have just read atoi() returns no errors. It returns an int though and the value of the int is supposed to be the value of the conversion. It seems to me that right there tells you if there was...
10
by: 66650755 | last post by:
First,thanks for all who have answered my last question. if char string="12345"; how could I convert the string(that is "3") to an int by using atoi? I only want to convert...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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,...

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.