943,972 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Marked Solved
  • Views: 607
  • C++ RSS
Oct 8th, 2009
0

question about string element

Expand Post »
I got a question about c++ strings.

Let's say string text = "0R14"

and I access each element using text[0],text[1] etc

does text[0] return an integer 0? or a character '0'?

if it doesn't return an integer, how do I convert individual string element to integer type if I need to do integer calculations?
Similar Threads
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
number87 is offline Offline
83 posts
since Jan 2008
Oct 8th, 2009
0
Re: question about string element
atoi("0");
(int ) text[0]-48
Reputation Points: 48
Solved Threads: 1
Light Poster
NeoKyrgyz is offline Offline
38 posts
since Jan 2009
Oct 8th, 2009
0
Re: question about string element
will atoi(text[0]) work too?
because doing atoi("0") is hardcoding....
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
number87 is offline Offline
83 posts
since Jan 2008
Oct 8th, 2009
3
Re: question about string element
atoi(text[0]) will not work because atoi expects a char*, not a char. That half of NeoKyrgyz's answer was basically useless and dumb.

If you want to convert the character "c" representing the decimal digit n to the integer n, you can do so with (c - '0') . That's the same as what NeoKyrgyz said, because '0' is just a fancy way of writing 48 . You'll note that '0' == 48, '1' == 49, ..., '9' == 57. If text is a string containing "0R14", then text[0] will evaluate to 48.

atoi is for converting c-style strings containing sequences of digits into numbers, e.g. "123" -> 123
Team Colleague
Reputation Points: 1135
Solved Threads: 172
Super Senior Demiposter
Rashakil Fol is offline Offline
2,479 posts
since Jun 2005
Oct 8th, 2009
0
Re: question about string element
thanks alot for explaining!
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
number87 is offline Offline
83 posts
since Jan 2008

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: animate a triangle in c
Next Thread in C++ Forum Timeline: Multiple "cout"s and "if"s within an If statement





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC