473,668 Members | 2,654 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question about atoi

The following description of atoi is pasted from cplusplus.com. My
question is after the pasting.

***** PASTING BEGINS HERE ******

int atoi ( const char * str ); <cstdlib>

Convert string to integer

Parses the C string str interpreting its content as an integral
number, which is returned as an int value.

The function first discards as many whitespace characters as necessary
until the first non-whitespace character is found. Then, starting from
this character, takes an optional initial plus or minus sign followed
by as many numerical digits as possible, and interprets them as a
numerical value.

The string can contain additional characters after those that form the
integral number, which are ignored and have no effect on the behavior
of this function.

If the first sequence of non-whitespace characters in str is not a
valid integral number, or if no such sequence exists because either
str is empty or it contains only whitespace characters, no conversion
is performed.
Parameters
str
C string beginning with the representation of an integral number.

Return Value
On success, the function returns the converted integral number as an
int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values,
INT_MAX or INT_MIN is returned.

**** PASTING ENDS HERE ***************

I don't know whether I'm missing something but this function seems to
have a serious flaw. If the value returned is 0, it seems that the
user can't know if this means no valid conversion or this means the
string begins with "0".

Any comments?

Paul Epstein

Oct 30 '07 #1
3 4182
pa**********@at t.net wrote:

<snippage>
>
I don't know whether I'm missing something but this function seems to
have a serious flaw. If the value returned is 0, it seems that the
user can't know if this means no valid conversion or this means the
string begins with "0".

Any comments?
Yes, don't use atoi() unless you know for certain the argument will be
in range. Otherwise, use strtol().

--
Ian Collins.
Oct 30 '07 #2
On Mon, 29 Oct 2007 20:20:30 -0700, pa**********@at t.net wrote in
comp.lang.c++:
The following description of atoi is pasted from cplusplus.com. My
question is after the pasting.

***** PASTING BEGINS HERE ******

int atoi ( const char * str ); <cstdlib>

Convert string to integer

Parses the C string str interpreting its content as an integral
number, which is returned as an int value.

The function first discards as many whitespace characters as necessary
until the first non-whitespace character is found. Then, starting from
this character, takes an optional initial plus or minus sign followed
by as many numerical digits as possible, and interprets them as a
numerical value.

The string can contain additional characters after those that form the
integral number, which are ignored and have no effect on the behavior
of this function.

If the first sequence of non-whitespace characters in str is not a
valid integral number, or if no such sequence exists because either
str is empty or it contains only whitespace characters, no conversion
is performed.
Parameters
str
C string beginning with the representation of an integral number.

Return Value
On success, the function returns the converted integral number as an
int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values,
INT_MAX or INT_MIN is returned.
This last statement is completely wrong. Whoever maintains this site
has made a serious mistake. The C++ standard does not specify the
exact behavior of this function, it merely refers to the C standsrd's
definition.

And here is what the C standard specifically states about this
function, which the C++ standard adopts by reference:

"The functions atof, atoi, atol, and atoll need not affect the value
of the integer expression errno on an error. If the value of the
result cannot be represented, the behavior is undefined."

That means that atoi() is not required, and most likely does not,
return INT_MAX or INT_MIN if the value is out of range, instead the
result is undefined behavior.

As Ian said, this function is unsafe for that reason. If you need to
convert a C string directly into numeric input, use strtol() or
strtoul().

See http://jk-technology.com/c/code/strtol.html for an example,
including how to tell the difference between an actual input of 0 and
invalid input.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Oct 31 '07 #3
On Oct 31, 3:57 am, Jack Klein <jackkl...@spam cop.netwrote:

[...[
That means that atoi() is not required, and most likely does not,
return INT_MAX or INT_MIN if the value is out of range, instead the
result is undefined behavior.
It's not required to, but as a QoI issue, I certainly would
expect it to. Both VC++ and the libc bundled with Linux do
behave well; I suspect that it is only very old libc bundled
with some traditional Unix which cause problems.

Of course, I'd still recommend something more robust, based on
strtol, but if you have an implementation of reasonable quality,
atoi should work as well.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Oct 31 '07 #4

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

Similar topics

19
7436
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()" for more information. > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback
6
16044
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 PushUnique(int); for(y = 0; y < 9; y++)
7
2313
by: Rick | last post by:
Hi, Another newbie question. I'm trying to convert a char to an integer. My input is a string which holds a number on place 4. However, if I try int number = atoi( input ); I'll get an error because of the type conversion I guess. Atoi wants a string while I put a single char into it. So I tried it another way: char s; int number; s = input;
15
29203
by: puzzlecracker | last post by:
does anyone know how to implement this function efficiently?
5
313
by: frankb.mail | last post by:
Ok i'm new to C++ and am teaching myself i've hit a small block that I can't seem to get around I am trying to convert an array like std::string load; into a float array. The code looks like this: float flaod;
9
4028
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; void main() { int atoi(char c);
48
384
by: Bill Cunningham | last post by:
This program is far from complete but I think there's something wrong in the mf line. Which means "money flow". Other than that I have no idea what is wrong here. The formula calls for tp_price X vol. Vol is an int and tp_price is a double and I'm multiplying the two. Is this legal? #include <stdio.h> int main(int argc, char *argv) { if (argc != 5)
50
5215
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 success or not. Am I wrong? Bill
10
4169
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 string,not other string. I've written these sentences: int a;
0
8381
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8893
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8583
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8656
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7401
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6209
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4380
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2023
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1786
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.