converting a character in a string to an integer

R

ross.oneill

Hi,

I have a string
strcpy(str, "2A");

and I want to grab the char 2 and convert it to an integer.

I tried doing this

int num = atoi(str[0]);

and it will not compile.

Any suggestions

Thanks
-R
 
W

Walter Roberson

I have a string
strcpy(str, "2A");
and I want to grab the char 2 and convert it to an integer.
I tried doing this
int num = atoi(str[0]);
and it will not compile.

atoi() must be passed a const char *str, but str[0] is just a plain char.
Even with automatic promotion into a const char, that's still a difference
of char vs pointer-to-char .

What is your general rule for such inputs? That there is -exactly-
one digit, which will be followed by something that is not a digit?
That you only want to convert one digit no matter what follows
(including possibly another digit)? That there might be several
digits, followed by something that is not a digit?

atoi() stops parsing when it finds something that isn't a valid
digit... but watch out for the boundary case where the input
does not start start with a digit. See also strtoul() and kin,
which have much better error reporting.

If you have exactly one digit, you could just use
int num = str[0]-'0';
 
P

pete

Walter said:
I have a string
strcpy(str, "2A");
and I want to grab the char 2 and convert it to an integer.
I tried doing this
int num = atoi(str[0]);
and it will not compile.
What is your general rule for such inputs? That there is -exactly-
one digit, which will be followed by something that is not a digit?
That you only want to convert one digit no matter what follows
(including possibly another digit)?

If that's the rule, then it's simple.

int num = "2A"[0] - '0';
 
B

Barry Schwarz

Hi,

I have a string
strcpy(str, "2A");

and I want to grab the char 2 and convert it to an integer.

I tried doing this

int num = atoi(str[0]);

What type of argument does atoi take? What is the type of str[0]? If
the value in str had been "29", would you still want only the 2?
and it will not compile.


<<Remove the del for email>>
 
P

pemo

pete said:
Walter said:
I have a string
strcpy(str, "2A");
and I want to grab the char 2 and convert it to an integer.
I tried doing this
int num = atoi(str[0]);
and it will not compile.
What is your general rule for such inputs? That there is -exactly-
one digit, which will be followed by something that is not a digit?
That you only want to convert one digit no matter what follows
(including possibly another digit)?

If that's the rule, then it's simple.

int num = "2A"[0] - '0';

Nice.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top