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

Char * to int

Kay
Is it possible to convert char * to integer ?
if yes, how to do it ?

Jul 22 '05 #1
15 9483
Kay wrote:
Is it possible to convert char * to integer ?
if yes, how to do it ?


char const * z = "12";

stringstream stream = z;
int q = 0;

if (z >> q)
cout << "yes" << endl;

(strtol() also works.)

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 22 '05 #2
"Kay" <er*********@yahoo.com.hk> wrote in message
news:41**************@yahoo.com.hk...
Is it possible to convert char * to integer ?
No, not portably.
if yes, how to do it ?


Perhaps you want to convert the textual representation
of a number to an integer type. If so, use a stringstream.

#include <iostream>
#include <sstream>

int main()
{
const char *x = "123";
std::istringstream iss(x);
int i(0);

if(iss >> i)
std::cout << i << '\n';
else
std::cerr << "unable to convert\n";

return 0;
}
-Mike
Jul 22 '05 #3
"Kay" <er*********@yahoo.com.hk> wrote in message
news:41**************@yahoo.com.hk...
Is it possible to convert char * to integer ?
if yes, how to do it ?


The technique listed in the FAQ for converting std::strings to numbers will
also work for C-style strings. See the FAQ
(http://www.parashift.com/c++-faq-lite/), section 38 ("Miscellaneous
technical issues"), question 2 ("How do I convert a std::string to a
number?").

--
David Hilsee
Jul 22 '05 #4

"Phlip" <ph*******@yahoo.com> wrote in message
news:Nj******************@newssvr17.news.prodigy.c om...
Kay wrote:
Is it possible to convert char * to integer ?
if yes, how to do it ?


char const * z = "12";

stringstream stream = z;
int q = 0;

if (z >> q)
cout << "yes" << endl;

(strtol() also works.)

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces


Isn't using 'atoi' function in <stdlib.h> much simpler?
Jul 22 '05 #5
Method Man wrote:
> Is it possible to convert char * to integer ?
> if yes, how to do it ?


char const * z = "12";

stringstream stream = z;
int q = 0;

if (z >> q)
cout << "yes" << endl;

(strtol() also works.)


Isn't using 'atoi' function in <stdlib.h> much simpler?


Yes, but it's also much worse, because it has a design bug. It doesn't
provide any way to find out whether the conversion was successful.

Jul 22 '05 #6

"Method Man" <a@b.c> wrote in message
news:1L*********************@read2.cgocable.net...

"Phlip" <ph*******@yahoo.com> wrote in message
news:Nj******************@newssvr17.news.prodigy.c om...
Kay wrote:
Is it possible to convert char * to integer ?
if yes, how to do it ?


char const * z = "12";

stringstream stream = z;
int q = 0;

if (z >> q)
cout << "yes" << endl;

(strtol() also works.)

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces


Isn't using 'atoi' function in <stdlib.h> much simpler?


Yes, but it cannot be used safely. (Does not protect from
overflow, which would cause undefined behavior. Also, a
valid result of zero cannot be distinguished from an error,
which 'atoi()' indicates by returning zero.

-Mike
Jul 22 '05 #7
Method Man wrote:

"Phlip" <ph*******@yahoo.com> wrote in message
news:Nj******************@newssvr17.news.prodigy.c om...
Kay wrote:
Is it possible to convert char * to integer ?
if yes, how to do it ?


char const * z = "12";

stringstream stream = z;
int q = 0;

if (z >> q)
cout << "yes" << endl;

(strtol() also works.)

--
Phlip

http://industrialxp.org/community/bi...rstUserInterfa
ces


Isn't using 'atoi' function in <stdlib.h> much simpler?


Simpler, perhaps. It has no error handling capability though. It's
generally recommended to you strtol() if you want to use C-style
functionality.
Brian Rodenborn
Jul 22 '05 #8

"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:f6*****************@newsread1.news.pas.earthl ink.net...

"Method Man" <a@b.c> wrote in message
news:1L*********************@read2.cgocable.net...

"Phlip" <ph*******@yahoo.com> wrote in message
news:Nj******************@newssvr17.news.prodigy.c om...
Kay wrote:

> Is it possible to convert char * to integer ?
> if yes, how to do it ?

char const * z = "12";

stringstream stream = z;
int q = 0;

if (z >> q)
cout << "yes" << endl;

(strtol() also works.)

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces


Isn't using 'atoi' function in <stdlib.h> much simpler?


Yes, but it cannot be used safely. (Does not protect from
overflow, which would cause undefined behavior. Also, a
valid result of zero cannot be distinguished from an error,
which 'atoi()' indicates by returning zero.

-Mike


Hmm, I would just write my own version of 'atoi' then. At the least, it's
good practice for a C/C++ job interview. ;)
Jul 22 '05 #9
"Method Man" <a@b.c> wrote in message
news:76*****************@read1.cgocable.net...

"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:f6*****************@newsread1.news.pas.earthl ink.net...

"Method Man" <a@b.c> wrote in message
news:1L*********************@read2.cgocable.net...

"Phlip" <ph*******@yahoo.com> wrote in message
news:Nj******************@newssvr17.news.prodigy.c om... >
> (strtol() also works.) Isn't using 'atoi' function in <stdlib.h> much simpler?


Yes, but it cannot be used safely. (Does not protect from
overflow, which would cause undefined behavior. Also, a
valid result of zero cannot be distinguished from an error,
which 'atoi()' indicates by returning zero.

-Mike


Hmm, I would just write my own version of 'atoi' then. At the least, it's
good practice for a C/C++ job interview. ;)


Why would you not use 'strto(u)l()'?

If a candidate wasted time reinventing what the standard library
already has, I would not be impressed. I'd be more impressed with
one who knows which tools are available, and when/how/where to apply
them.

Anyone familiar with C or C++ will recognize 'strtol()' at a glance,
whereas upon encountering a 'home-grown' conversion function, one
would need to find out what the darn thing actually does. Also, a
standard library function has a far better chance of being fully
debugged and robust.
-Mike
Jul 22 '05 #10
Kay <er*********@yahoo.com.hk> wrote:
Is it possible to convert char * to integer ?
if yes, how to do it ?


<http://www.boost.org/libs/conversion/lexical_cast.htm>

int main(int argc, char * argv[])
{
using boost::lexical_cast;
using boost::bad_lexical_cast;

std::vector<short> args;

while(*++argv)
{
try
{
args.push_back(lexical_cast<short>(*argv));
}
catch(bad_lexical_cast &)
{
args.push_back(0);
}
}
...
}

There you go...
Jul 22 '05 #11

"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:qg****************@newsread1.news.pas.earthli nk.net...
"Method Man" <a@b.c> wrote in message
news:76*****************@read1.cgocable.net...

"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:f6*****************@newsread1.news.pas.earthl ink.net...

"Method Man" <a@b.c> wrote in message
news:1L*********************@read2.cgocable.net...
>
> "Phlip" <ph*******@yahoo.com> wrote in message
> news:Nj******************@newssvr17.news.prodigy.c om... >
> > (strtol() also works.) Isn't using 'atoi' function in <stdlib.h> much simpler?

Yes, but it cannot be used safely. (Does not protect from
overflow, which would cause undefined behavior. Also, a
valid result of zero cannot be distinguished from an error,
which 'atoi()' indicates by returning zero.

-Mike


Hmm, I would just write my own version of 'atoi' then. At the least, it's good practice for a C/C++ job interview. ;)


Why would you not use 'strto(u)l()'?

If a candidate wasted time reinventing what the standard library
already has, I would not be impressed. I'd be more impressed with
one who knows which tools are available, and when/how/where to apply
them.

Anyone familiar with C or C++ will recognize 'strtol()' at a glance,
whereas upon encountering a 'home-grown' conversion function, one
would need to find out what the darn thing actually does. Also, a
standard library function has a far better chance of being fully
debugged and robust.
-Mike


Yes, you're right.

I guess I've always used 'atoi'. This is what I was taught back in my 1st
year university CS class for converting any C-style strings to int.

Regarding the interview question. I've actually been asked to specifically
implement 'atoi' in two separate interviews. I suppose the context was
simply that it's a good test for one's pointer knowledge and error handling
ability with strings.
Jul 22 '05 #12
Method Man wrote:

I guess I've always used 'atoi'. This is what I was taught back in my 1st
year university CS class for converting any C-style strings to int.

Regarding the interview question. I've actually been asked to specifically
implement 'atoi' in two separate interviews. I suppose the context was
simply that it's a good test for one's pointer knowledge and error handling
ability with strings.


int atoi( char* String )
{
int Result;
sscanf( "%d", Result );
return Result;
}

:-)

I guess this is not what your interviewer expected you to do :-)

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #13

"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:41***************@gascad.at...
Method Man wrote:

I guess I've always used 'atoi'. This is what I was taught back in my 1st year university CS class for converting any C-style strings to int.

Regarding the interview question. I've actually been asked to specifically implement 'atoi' in two separate interviews. I suppose the context was
simply that it's a good test for one's pointer knowledge and error handling ability with strings.
int atoi( char* String )
{
int Result;
sscanf( "%d", Result );

return (sscanf(String, "%d", &Result) == 1) ? Result : 0;
return Result;
}


-Mike
Jul 22 '05 #14
Method Man wrote:
Hmm, I would just write my own version of 'atoi' then. At the least,
it's good practice for a C/C++ job interview. ;)


If asked to write atoi() at a job interview, I would match its exact ISO
specification, verbally point out all its minor flaws, reveal when and when
not I would use it, and write wrapper code that defends its calls.

(Not sure if I could match the performance with lexical_cast, though!)

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 22 '05 #15
Phlip wrote:
Method Man wrote:
Hmm, I would just write my own version of 'atoi' then. At the least,
it's good practice for a C/C++ job interview. ;)
If asked to write atoi() at a job interview, I would match its exact ISO
specification, verbally point out all its minor flaws,


It has minor flaws too?
reveal when and when not I would use it, and write wrapper code that
defends its calls.


If asked to write it, I'd write it. Nothing more. If they want to know more,
they can ask. Well, maybe I'd just note that atoi() is a bad idea because
has a major design bug.
It's just like in oral exams. Don't answer questions that have not been
asked.

Jul 22 '05 #16

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

Similar topics

9
by: Christopher Benson-Manica | last post by:
I need a smart char * class, that acts like a char * in all cases, but lets you do some std::string-type stuff with it. (Please don't say to use std::string - it's not an option...). This is my...
5
by: Alex Vinokur | last post by:
"Richard Bos" <rlb@hoekstra-uitgeverij.nl> wrote in message news:4180f756.197032434@news.individual.net... to news:comp.lang.c > ben19777@hotmail.com (Ben) wrote: > > 2) Structure casted into an...
5
by: Sona | last post by:
I understand the problem I'm having but am not sure how to fix it. My code passes two char* to a function which reads in some strings from a file and copies the contents into the two char*s. Now...
2
by: Peter Nilsson | last post by:
In a post regarding toupper(), Richard Heathfield once asked me to think about what the conversion of a char to unsigned char would mean, and whether it was sensible to actually do so. And pete has...
5
by: jab3 | last post by:
(again :)) Hello everyone. I'll ask this even at risk of being accused of not researching adequately. My question (before longer reasoning) is: How does declaring (or defining, whatever) a...
12
by: GRoll35 | last post by:
I get 4 of those errors. in the same spot. I'll show my parent class, child class, and my driver. All that is suppose to happen is the user enters data and it uses parent/child class to display...
18
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
4
by: Paul Brettschneider | last post by:
Hello all, consider the following code: typedef char T; class test { T *data; public: void f(T, T, T); void f2(T, T, T);
16
by: s0suk3 | last post by:
This code #include <stdio.h> int main(void) { int hello = {'h', 'e', 'l', 'l', 'o'}; char *p = (void *) hello; for (size_t i = 0; i < sizeof(hello); ++i) {
29
by: Kenzogio | last post by:
Hi, I have a struct "allmsg" and him member : unsigned char card_number; //16 allmsg.card_number
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
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: 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:
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
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.