![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Professional Programmer
Join Date: Jan 2006
Location: Ontario, Canada
Posts: 376
Rep Power: 0
![]() |
How can I convert a char[] to int without using atoi?
__________________
I am Addicted to Linux! |
|
|
|
|
#2 |
|
Newbie
Join Date: Dec 2005
Posts: 12
Rep Power: 0
![]() |
int(variable)
|
|
|
|
|
#3 |
|
Professional Programmer
Join Date: Jan 2006
Location: Ontario, Canada
Posts: 376
Rep Power: 0
![]() |
doesnt work
__________________
I am Addicted to Linux! |
|
|
|
|
#4 |
|
Expert Programmer
Join Date: Jun 2005
Posts: 852
Rep Power: 4
![]() |
Why would you want to? Perhaps for a programming class?
Think about how you might approach this if you were doing it step by step on paper. One way is to go through each character in the char[] and convert it to an integer value, keeping a running total in an int. Each time you process a new character, multiply the current running total by 10 and add in the integer value of the char. Give it a go and if you get into trouble, post your code here. |
|
|
|
|
#5 |
|
Professional Programmer
Join Date: Sep 2005
Location: serbia & montenegro
Posts: 484
Rep Power: 4
![]() |
Do you want to create your function or only use a different one from atoi()?
|
|
|
|
|
#6 |
|
Programmer
Join Date: Dec 2005
Posts: 33
Rep Power: 0
![]() |
Use strtol function. Its safer than atoi.
__________________
The only real valuable thing is intuition. -Albert Einstein |
|
|
|
|
#7 | |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
Quote:
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#8 |
|
Professional Programmer
Join Date: Jan 2006
Location: Ontario, Canada
Posts: 376
Rep Power: 0
![]() |
I got it working, thanks for the replies
__________________
I am Addicted to Linux! |
|
|
|
|
#9 |
|
Newbie
Join Date: Jan 2006
Posts: 13
Rep Power: 0
![]() |
If you're using doing this in c++ why are you even using a char array to manage strings of characters?
I recommend you use std::string to manage strings of characters. To convert integer values that are represented in a string use std::stringstream. Here's a function I normally use to do this. You might want to make it inline. int StringToInt(const std::string& str) // string to int
{
stringstream l_ss(str);
int l_rint;
l_ss >> l_rint; // casting from string to int...
return l_rint;
} |
|
|
|
|
#10 | |
|
Expert Programmer
Join Date: Aug 2005
Location: Rotterdam, the Netherlands
Posts: 942
Rep Power: 4
![]() |
Quote:
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|