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

Standard Library function converting char[] to int?

I know I can write one, or use QString, etc., but is there a native C++
function to convert a NTBS of digits to an integer?
--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell

Jul 22 '05 #1
9 3610

"Steven T. Hatton" <su******@setidava.kushan.aa> wrote in message
news:HL********************@speakeasy.net...
|I know I can write one, or use QString, etc., but is there a native C++
| function to convert a NTBS of digits to an integer?

[snip]

For straight out of the box, the following will do:

// Non-Preferred...
'std::atoi()'

// Much-Preferred...
'std::strtol()' and 'std::strtoul()'

Cheers.
Chris Val
Jul 22 '05 #2
Chris ( Val ) wrote:

"Steven T. Hatton" <su******@setidava.kushan.aa> wrote in message
news:HL********************@speakeasy.net...
|I know I can write one, or use QString, etc., but is there a native C++
| function to convert a NTBS of digits to an integer?

[snip]

For straight out of the box, the following will do:

// Non-Preferred...
'std::atoi()'

// Much-Preferred...
'std::strtol()' and 'std::strtoul()'

Cheers.
Chris Val


Thanks. I should have looked in K&R. Have a good laugh at my expense:

size_t ntbs2size_t(char* intStr) {
size_t result = 0;

while (*intStr != 0) {
if(!isdigit(*intStr))
{
throw invalid_argument("cstr2size_t: argument not a digit.\n");
}

result = (result * 10) + (*intStr - '0');
intStr++;
}
return result;
}

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell

Jul 22 '05 #3
On Fri, 22 Oct 2004 08:52:08 -0400, "Steven T. Hatton"
<su******@setidava.kushan.aa> wrote:
I know I can write one, or use QString, etc., but is there a native C++
function to convert a NTBS of digits to an integer?


Depends on whether the string represents an integer which fits into
the integer supported by your system.

Neither strtol nor strtod are "native C++ functions", but functions
defined by the C runtime library. Of course, strtol will also fail if
the string is too large.

Anyway, here is a purely C++ solution using the STL:

#include <iostream>
#include <ostream>
#include <sstream>

int main()
{
using namespace std;
int a;
char const * pc = "1234567890";
std::istringstream iss(pc);
iss >> a;
cout << "Number is: " << a << endl;
return 0;
}

--
Bob Hairgrove
No**********@Home.com
Jul 22 '05 #4
Steven T. Hatton wrote:
[...] Have a good laugh at my expense:

size_t ntbs2size_t(char* intStr) {
Better to declare the argument as 'const char*'. And you never check
the 'intStr' for being null either. But that's OK if you document
that your function has UB if a null pointer is passed to it.
size_t result = 0;

while (*intStr != 0) {
if(!isdigit(*intStr))
{
throw invalid_argument("cstr2size_t: argument not a digit.\n");
}

result = (result * 10) + (*intStr - '0');
intStr++;
}
return result;
}


Hey, that's not all that bad an implementation of 'atoi'. Has some error
checking as well.

V
Jul 22 '05 #5

"Bob Hairgrove" <in*****@bigfoot.com> wrote in message
news:n3********************************@4ax.com...
| On Fri, 22 Oct 2004 08:52:08 -0400, "Steven T. Hatton"
| <su******@setidava.kushan.aa> wrote:
|
| >I know I can write one, or use QString, etc., but is there a native C++
| >function to convert a NTBS of digits to an integer?
|
| Depends on whether the string represents an integer which fits into
| the integer supported by your system.
|
| Neither strtol nor strtod are "native C++ functions", but functions
| defined by the C runtime library. Of course, strtol will also fail if
| the string is too large.
|
| Anyway, here is a purely C++ solution using the STL:
|
| #include <iostream>
| #include <ostream>
| #include <sstream>
|
| int main()
| {
| using namespace std;
| int a;
| char const * pc = "1234567890";
| std::istringstream iss(pc);
| iss >> a;
| cout << "Number is: " << a << endl;
| return 0;
| }

If you want that to work safely, then you'll need
to add some error checking, otherwise it too can
fail miserably.

Cheers.
Chris Val
Jul 22 '05 #6
On Sat, 23 Oct 2004 19:34:38 +1000, "Chris \( Val \)"
<ch******@bigpond.com.au> wrote:

"Bob Hairgrove" <in*****@bigfoot.com> wrote in message
news:n3********************************@4ax.com.. .
| On Fri, 22 Oct 2004 08:52:08 -0400, "Steven T. Hatton"
| <su******@setidava.kushan.aa> wrote:
|
| >I know I can write one, or use QString, etc., but is there a native C++
| >function to convert a NTBS of digits to an integer?
|
| Depends on whether the string represents an integer which fits into
| the integer supported by your system.
|
| Neither strtol nor strtod are "native C++ functions", but functions
| defined by the C runtime library. Of course, strtol will also fail if
| the string is too large.
|
| Anyway, here is a purely C++ solution using the STL:
|
| #include <iostream>
| #include <ostream>
| #include <sstream>
|
| int main()
| {
| using namespace std;
| int a;
| char const * pc = "1234567890";
| std::istringstream iss(pc);
| iss >> a;
| cout << "Number is: " << a << endl;
| return 0;
| }

If you want that to work safely, then you'll need
to add some error checking, otherwise it too can
fail miserably.


Hmm ... just tried a huge number. I thought that if the number
represented by the string were too large, istream::operator>> should
throw an exception. But it doesn't!

Here's an improved version:

#include <iostream>
#include <ostream>
#include <sstream>
#include <stdexcept>
#include <limits>

int main()
{
using namespace std;
try
{
int a;
double d;
char const * pc = "12345678901234567890";
std::istringstream iss(pc);
iss >> d;
if (d <= numeric_limits<int>::max()
&& d >= numeric_limits<int>::min())
{
a = static_cast<int>(d);
cout << "Number is: " << a << endl;
}
else
{
cout << "Error: number " << iss.str();
cout << " is out of range for int." << endl;
}
}
catch(const std::exception &e)
{
cout << "Error: " << e.what() << endl;
}
return 0;
}

--
Bob Hairgrove
No**********@Home.com
Jul 22 '05 #7

"Bob Hairgrove" <in*****@bigfoot.com> wrote in message
news:04********************************@4ax.com...
| On Sat, 23 Oct 2004 19:34:38 +1000, "Chris \( Val \)"
| <ch******@bigpond.com.au> wrote:

[snip]

| >| int main()
| >| {
| >| using namespace std;
| >| int a;
| >| char const * pc = "1234567890";
| >| std::istringstream iss(pc);
| >| iss >> a;
| >| cout << "Number is: " << a << endl;
| >| return 0;
| >| }
| >
| >If you want that to work safely, then you'll need
| >to add some error checking, otherwise it too can
| >fail miserably.
|
| Hmm ... just tried a huge number. I thought that if the number
| represented by the string were too large, istream::operator>> should
| throw an exception. But it doesn't!

That will only happen if you turn 'istream::exceptions()'
on manually, by setting the appropriate bit mask(s), but
it is not always ideal, and still requires further code
to make it safe, I think.

| Here's an improved version:
|
| #include <iostream>
| #include <ostream>
| #include <sstream>
| #include <stdexcept>
| #include <limits>
|
| int main()
| {
| using namespace std;
| try
| {
| int a;
| double d;
| char const * pc = "12345678901234567890";
| std::istringstream iss(pc);
| iss >> d;
| if (d <= numeric_limits<int>::max()
| && d >= numeric_limits<int>::min())
| {
| a = static_cast<int>(d);
| cout << "Number is: " << a << endl;
| }
| else
| {
| cout << "Error: number " << iss.str();
| cout << " is out of range for int." << endl;
| }
| }
| catch(const std::exception &e)
| {
| cout << "Error: " << e.what() << endl;
| }
| return 0;
| }

It's not that much safer than the original :-)

If I change the number to represent:
char const * pc = "1.234";

....the result is '1', clearly incorrect.

It also does not accommodate for trailing white space,
where as the 'strto*' functions do.

You can check it for this, as well as eof() condition,
which should do the trick:

template<typename T>
inline T ConvertTo( const char* const Source )
{
T Value( 0 );
std::istringstream Iss( Source );

if( !( Iss >> Value >> std::ws && Iss.eof() ) )
{
throw std::runtime_error(
"ERROR: Could not convert source string. " );
}

return Value;
}

int main()
{
std::string N( "123" );

try
{
std::cout << ConvertTo<int>( N.c_str() ) << std::endl;
}
catch( const std::runtime_error& e )
{
std::cerr << e.what() << std::endl;
}

return 0;
}

Cheers.
Chris Val
Jul 22 '05 #8
On Sat, 23 Oct 2004 23:40:50 +1000, "Chris \( Val \)"
<ch******@bigpond.com.au> wrote:
If I change the number to represent:
char const * pc = "1.234";

...the result is '1', clearly incorrect.

It also does not accommodate for trailing white space,
where as the 'strto*' functions do.


Yes, but the OP requested a way to convert a "NTBS of digits" ... not
a string containing random characters. Presumably the OP would have
checked the input first.

--
Bob Hairgrove
No**********@Home.com
Jul 22 '05 #9

"Bob Hairgrove" <in*****@bigfoot.com> wrote in message
news:dv********************************@4ax.com...
| On Sat, 23 Oct 2004 23:40:50 +1000, "Chris \( Val \)"
| <ch******@bigpond.com.au> wrote:
|
| >If I change the number to represent:
| > char const * pc = "1.234";
| >
| >...the result is '1', clearly incorrect.
| >
| >It also does not accommodate for trailing white space,
| >where as the 'strto*' functions do.
|
| Yes, but the OP requested a way to convert a "NTBS of digits"

Yes, that is correct.

| ... not a string containing random characters.

Are you saying that this is not an check worth performing ?

| Presumably the OP would have checked the input first.

Well, 'std::strto*' functions do that for you (discard
white space), as well as check for inappropriate chars,
so why shouldn't we model our 'std::stringstream' version
on the behaviour and principles of it's *robust* predecessors ?

Cheers.
Chris Val


Jul 22 '05 #10

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

Similar topics

1
by: Mark McEahern | last post by:
I just wrote a very simple wrapper for the PayFlow Pro SDK (see below). A friend of mine did this before, but I didn't have access to his source, so I took it as a learning opportunity for me to...
43
by: Steven T. Hatton | last post by:
Now that I have a better grasp of the scope and capabilities of the C++ Standard Library, I understand that products such as Qt actually provide much of the same functionality through their own...
41
by: Greenhorn | last post by:
Hi, We see that C is a bit liberal towards non-standard syntax, for e.g. when i tried <printf("string1", "string2 %d", v1);> in Dev-C++, it printed string1 and no error was raised, is this the...
6
by: Frederick Gotham | last post by:
I gather that, rather than the C++ Standard defining the functionality of the Standard Library features which it has in common with C, it makes reference to a C Standard which defines their...
7
by: Lighter | last post by:
Is overriding a function of a library in accordance with C++ standard? The following code are passed by the VS 2005 and Dev C++. #include <cstdlib> #include <iostream> using namespace std;...
7
by: Francine.Neary | last post by:
This may well be implementation-defined or undefined behavior... if so, then of course that's a good enough answer. Consider the following situation: /* file1.c */ int (*f)(const char *,...
270
by: jacob navia | last post by:
In my "Happy Christmas" message, I proposed a function to read a file into a RAM buffer and return that buffer or NULL if the file doesn't exist or some other error is found. It is interesting...
40
by: Angus | last post by:
Hello I am writing a library which will write data to a user defined callback function. The function the user of my library will supply is: int (*callbackfunction)(const char*); In my...
4
by: screamer81 | last post by:
Hello, I've a SDK functions description for a scanner and I try to convert unmanaged DLL C++ functions to c#. I converted all except one of them. This function is getting a struct parameter. ...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: 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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.