473,671 Members | 2,283 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

atoi() equivilent without exceptions?

Hello,

I'm a .NET newbie but have 12 years of C++/MFC.

In C++, atoi() stops converting at the first non-digit, so in this code,
octet will be 192:

int octet = atoi("192."); // <-- note '.' at end of this string
This is great, exactly what I want. But to achieve it in C++/CLI, the code
I am using is this:

try
{
int octet = Convert::ToInt1 6("192.");
}
catch (Exception^ )
{
// Convert::ToInt1 6 throws when there are non-digits in parameter
}
Because an exception is thrown, the conversion is not successful. This is
highly unusable! I've had to strip off the '.' so Convert::ToInt1 6() is
successful in the normal case.

However, if the string is malformed (doesn't contain any digits), the
exception is still thrown, whereas atoi() simply returns a value which I
skip. Maybe I'm misunderstandin g exceptions (I don't use them even in C++
when I can help it), but having to try/catch an exception instead of just
getting a simple return value seems to be adding complexity instead of
reducing it. I don't like replacing 1 line of C++ with 8 lines of .NET for
a simple conversion.

Is there a better way?

Thanks,
David (MVP - VC++)
Mar 3 '07 #1
5 5129
>Is there a better way?

Since it's C++/CLI, keep using atoi.

Dave
Mar 3 '07 #2
"David Ching" <dc@remove-this.dcsoft.com wrote in message
news:dw******** *******@newssvr 14.news.prodigy .net...
Hello,

I'm a .NET newbie but have 12 years of C++/MFC.

In C++, atoi() stops converting at the first non-digit, so in this code, octet will be
192:

int octet = atoi("192."); // <-- note '.' at end of this string
This is great, exactly what I want. But to achieve it in C++/CLI, the code I am using is
this:

try
{
int octet = Convert::ToInt1 6("192.");
}
catch (Exception^ )
{
// Convert::ToInt1 6 throws when there are non-digits in parameter
}
Because an exception is thrown, the conversion is not successful. This is highly
unusable! I've had to strip off the '.' so Convert::ToInt1 6() is successful in the normal
case.

However, if the string is malformed (doesn't contain any digits), the exception is still
thrown, whereas atoi() simply returns a value which I skip. Maybe I'm misunderstandin g
exceptions (I don't use them even in C++ when I can help it), but having to try/catch an
exception instead of just getting a simple return value seems to be adding complexity
instead of reducing it. I don't like replacing 1 line of C++ with 8 lines of .NET for a
simple conversion.

Is there a better way?

Thanks,
David (MVP - VC++)


Use the TryParse method like this:

int result;
if(Int32::TryPa rse("129.", result) == true)
Console::WriteL ine("{0}", result);
else
...
or the overload which allows you specify a Number style or/and a FormatProvider.

Willy.

Mar 3 '07 #3
"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:%2******** ********@TK2MSF TNGP06.phx.gbl. ..
Use the TryParse method like this:

int result;
if(Int32::TryPa rse("129.", result) == true)
Console::WriteL ine("{0}", result);
else
...
Thanks much Willy it worked somewhat. TryParse() returned false for "129."
since it didn't like the '.' at the end. Only whitespace is allowed after
the digits. But if I kept my code to remove the '.', then it worked, and I
don't have to try/catch an exception, saving code.

I need to look for the methods starting with "Try", as these seem to be the
ones that don't throw exceptions.

Thanks again,
David (MVP - VC++)
Mar 4 '07 #4
Hi David!
>>Use the TryParse method like this:

int result;
if(Int32::Try Parse("129.", result) == true)
Console::WriteL ine("{0}", result);
else
...

Thanks much Willy it worked somewhat. TryParse() returned false for "129."
since it didn't like the '.' at the end. Only whitespace is allowed after
the digits. But if I kept my code to remove the '.', then it worked, and I
don't have to try/catch an exception, saving code.
Take a look at the "NumberStyl es" enumeration!

The following works without any modification:

int i = 0;
Console::WriteL ine(
Int32::TryParse ("129.",
Globalization:: NumberStyles::N umber,
nullptr,
i)
);
Console::WriteL ine(i);

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
Mar 4 '07 #5
"Jochen Kalmbach [MVP]" <no************ ********@holzma .dewrote in message
news:uD******** ******@TK2MSFTN GP06.phx.gbl...
Take a look at the "NumberStyl es" enumeration!

The following works without any modification:

int i = 0;
Console::WriteL ine(
Int32::TryParse ("129.",
Globalization:: NumberStyles::N umber,
nullptr,
i)
);
Console::WriteL ine(i);
Thanks for the tip Jochen! Much appreciated.

-- David
Mar 4 '07 #6

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
8
1779
by: Sonia | last post by:
Hi, I've been using atoi for a while now, but would like to know how to implement one? Can anyone give me simple efficient implementation of that function? Or point me sowhere for reference. Everywhere I look the usage is described, but I cannot actually view the code itself. Thanks
4
3145
by: Darren | last post by:
Hi. I have a javascript menu system which uses the "elementFromPoint" function. However Netscape/Mozilla doesn't recognise this function. Does it have an equivilent? Thanks -- Darren
2
14326
by: francescomoi | last post by:
Hi. I'm trying to compile this piece of source: ------------------------------------------- int id; while(row1 = mysql_fetch_row(rs1)) { id = atoi((int)row1); -----------------------------------
11
3595
by: rayw | last post by:
I'm pretty new to C, although I did do some years ago now. I've been told that itoa is no longer a standard function, and that the ato... functions - although in the std - are not recommended. So, I was wondering what was wrong with both itoa and atoi etc (and what's replaced them). Many thanks
23
2976
by: tolkien | last post by:
Hi,My problem is this: I have : char matrix=.... int x; x=atoi(matrix); This doesn't work.Any help? I don't have any errors.Just a warning" passing argument 1 of 'atoi' makes pointer from integer without a cast"
11
4250
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 <stdlib.h> #include <string.h> int i;
4
2511
by: Ram | last post by:
Hi All, Firstly i am a newbie and trying to learn C. The background of the problem is Program: Presently I am working on a program of numerology and the I/P will be the name and output will be a digit for which there are known characteristics which i will print.
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
0
8400
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
8924
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...
0
8823
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8602
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
7441
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
6234
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...
1
2817
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2058
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1814
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.