std::string-to-int converter

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

User avatar
Ginto8
ES Beta Backer
ES Beta Backer
Posts: 1064
Joined: Tue Jan 06, 2009 4:12 pm
Programming Language of Choice: C/C++, Java

std::string-to-int converter

Post by Ginto8 »

Yes, I know that you can just use atoi(), but I was bored so I didn't care.

Note: this will treat the string as though there are no other characters in the string other than numbers, so if the string was "1a3", it would return 13.

Edit: Now it also works with negative numbers, so if you had "-q1a3", it would return -13

Code: Select all

int stringToInt(string str)
{
    int x = 0;
    for(int i = str.size() - 1, j = 1; i >= 0; --i)
    {
        char current = str[i];
        if(current >= '0' && current <= '9')
        {
            if(x < 0)
                x = abs(x);
            int y = (int)current - '0';
            x += y * j;
            j *= 10;
        }
        else if(current == '-')
            x *= -1;
    }
    return x;
}
I've tested it, so it should work. ;)

Edit2: I made a char* version:

Code: Select all

int stringToInt(char str[])
{
    int ret = 0, multiple = 1;
    char* ptr;
    for(ptr = str; *ptr; ++i)
    {;
        if(*ptr >= '0' && *ptr <= '9')
        {
            if(x < 0)
                x *= -1;
            int y = (int)(*ptr) - '0';
            x += y * multiple;
            multiple *= 10;
        }
        else if(*ptr == '-')
            x *= -1;
    }
    return x;
}
Last edited by Ginto8 on Tue Jul 07, 2009 2:26 pm, edited 5 times in total.
Quit procrastinating and make something awesome.
Ducky wrote:Give a man some wood, he'll be warm for the night. Put him on fire and he'll be warm for the rest of his life.
User avatar
sparda
Chaos Rift Junior
Chaos Rift Junior
Posts: 291
Joined: Tue Sep 23, 2008 3:54 pm

Re: std::string-to-int converter

Post by sparda »

Ginto8 wrote:So if the string was "1a3", it would return 13.
Actually, your function is better since atoi("1a3") would terminate at the first invalid (non integer) value. So atoi() would return 1, while yours returns 13. On second though, I retract; "better" would depend on the situation or what you're trying to do. So they both have their uses.

By the way, in Java (I've learning it in my spare time) you can also do something like this:

Code: Select all

Integer.parseInt("1a3");
;)
User avatar
MarauderIIC
Respected Programmer
Respected Programmer
Posts: 3406
Joined: Sat Jul 10, 2004 3:05 pm
Location: Maryland, USA

Re: std::string-to-int converter

Post by MarauderIIC »

Edit: There, I fixed it. For those curious, I had hit "edit" instead of "quote" and overwrote his post with my reply :)

My reply is,

Code: Select all

        if(!(current < '0' || current > '9'))
is equivalent to the clearer

Code: Select all

if (current >= '0' && current <= '9')
Very nice (assuming it works), btw - gj :D
Last edited by MarauderIIC on Fri Mar 27, 2009 7:04 pm, edited 1 time in total.
Reason: fixed <= >=, thanks ryan http://elysianshadows.com/phpBB3/viewtopic.php?p=37291#p37291
I realized the moment I fell into the fissure that the book would not be destroyed as I had planned.
wearymemory
Chaos Rift Junior
Chaos Rift Junior
Posts: 209
Joined: Thu Feb 12, 2009 8:46 pm

Re: std::string-to-int converter

Post by wearymemory »

sparda wrote:By the way, in Java (I've learning it in my spare time) you can also do something like this:

Code: Select all

Integer.parseInt("1a3");
;)
No you can't.
User avatar
sparda
Chaos Rift Junior
Chaos Rift Junior
Posts: 291
Joined: Tue Sep 23, 2008 3:54 pm

Re: std::string-to-int converter

Post by sparda »

wearymemory wrote:No you can't.
LULZ!

Here is the OFFICIAL java documentation for the Integer class. Apparently you're too lazy to search Google before posting erroneous remarks.
User avatar
RyanPridgeon
Chaos Rift Maniac
Chaos Rift Maniac
Posts: 447
Joined: Sun Sep 21, 2008 1:34 pm
Current Project: "Triangle"
Favorite Gaming Platforms: PC
Programming Language of Choice: C/C++
Location: UK
Contact:

Re: std::string-to-int converter

Post by RyanPridgeon »

MarauderIIC wrote:Edit: There, I fixed it. For those curious, I had hit "edit" instead of "quote" and overwrote his post with my reply :)

My reply is,

Code: Select all

        if(!(current < '0' || current > '9'))
is equivalent to the clearer

Code: Select all

if (current > '0' && current < '9')
Very nice (assuming it works), btw - gj :D

Code: Select all

if (current >= '0' && current <= '9')
Fixed.
Ryan Pridgeon
C, C++, C#, Java, ActionScript 3, HaXe, PHP, VB.Net, Pascal
Music | Blog
wearymemory
Chaos Rift Junior
Chaos Rift Junior
Posts: 209
Joined: Thu Feb 12, 2009 8:46 pm

Re: std::string-to-int converter

Post by wearymemory »

sparda wrote:
wearymemory wrote:No you can't.
LULZ!

Here is the OFFICIAL java documentation for the Integer class. Apparently you're too lazy to search Google before posting erroneous remarks.
I am? It's a shame you feel that way.

The line of code you've provided will throw a NumberFormatException.

I have a lot more experience with Java than you do. Not that you asked.
User avatar
sparda
Chaos Rift Junior
Chaos Rift Junior
Posts: 291
Joined: Tue Sep 23, 2008 3:54 pm

Re: std::string-to-int converter

Post by sparda »

wearymemory wrote:I am? It's a shame you feel that way.

The line of code you've provided will throw a NumberFormatException.

I have a lot more experience with Java than you do. Not that you asked.

LOLOLOLOLOL!!!

Oh my god LOL!

You are absolutely correct :mrgreen:

But you're also right that I never asked you for your credentials. In any case, you could have added A LITTLE MORE than simply:
No you can't.
Just for future reference.

Anything less, and I swear you were trying to flame-bait me. But I've learned my lesson, I won't even minutely comment about things I don't fully understand.
User avatar
Ginto8
ES Beta Backer
ES Beta Backer
Posts: 1064
Joined: Tue Jan 06, 2009 4:12 pm
Programming Language of Choice: C/C++, Java

Re: std::string-to-int converter

Post by Ginto8 »

Made some changes, added negatives. So if you entered "-q1a3", it would return -13, and if you entered "1q-a3", it would return 13. ;)
Quit procrastinating and make something awesome.
Ducky wrote:Give a man some wood, he'll be warm for the night. Put him on fire and he'll be warm for the rest of his life.
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: std::string-to-int converter

Post by avansc »

Ginto8 wrote:Made some changes, added negatives. So if you entered "-q1a3", it would return -13, and if you entered "1q-a3", it would return 13. ;)
what if you did "1qa-3"

anyways, this is a total waste of effort, there is not reason you need this.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
Scoody
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 65
Joined: Fri Feb 06, 2009 2:07 pm

Re: std::string-to-int converter

Post by Scoody »

avansc wrote:anyways, this is a total waste of effort, there is not reason you need this.
If he's learning by doing this, it wouldn't be a waste of effort.
User avatar
Ginto8
ES Beta Backer
ES Beta Backer
Posts: 1064
Joined: Tue Jan 06, 2009 4:12 pm
Programming Language of Choice: C/C++, Java

Re: std::string-to-int converter

Post by Ginto8 »

avansc wrote:
Ginto8 wrote:Made some changes, added negatives. So if you entered "-q1a3", it would return -13, and if you entered "1q-a3", it would return 13. ;)
what if you did "1qa-3"

anyways, this is a total waste of effort, there is not reason you need this.
"1qa-3" would do the same as "1q-a3".

And I think I said in the OP that I was bored when I made this. ;) :mrgreen: :lol:
Quit procrastinating and make something awesome.
Ducky wrote:Give a man some wood, he'll be warm for the night. Put him on fire and he'll be warm for the rest of his life.
User avatar
zodiac976
Chaos Rift Regular
Chaos Rift Regular
Posts: 156
Joined: Thu Jun 18, 2009 10:03 am
Current Project: Booklet & Text RPG
Favorite Gaming Platforms: PC, PS3, PSP
Programming Language of Choice: C++
Location: AL
Contact:

Re: std::string-to-int converter

Post by zodiac976 »

I prefer to use stringstream for converting than atoi, etc.

#include <sstream>

strings to whatever:
stringstream input(string variable);
input >> variable;

whatever to strings:
stringstream output;
output << variable;
output = variable.str();
User avatar
programmerinprogress
Chaos Rift Devotee
Chaos Rift Devotee
Posts: 632
Joined: Wed Oct 29, 2008 7:31 am
Current Project: some crazy stuff, i'll tell soon :-)
Favorite Gaming Platforms: PC
Programming Language of Choice: C++!
Location: The UK
Contact:

Re: std::string-to-int converter

Post by programmerinprogress »

I have a complete solution to this li'l problem, I use a little bit of bitmasking to convert my strings to integers, I just knocked this out when I was bored today

Code: Select all

#include<iostream>
#include<string>

using namespace std;



int StringToInt(const char* target); // char* means you can pass any kind of string
// just as long as you use .c_str() on a C++ string if it isnt literal

int main(int argc, char** argv)
{
        cout << StringToInt("cyrax thinks he's a 13x3x7 hax0r");
        return 0;
}

int StringToInt(const char* target)
{
       int multiple = 1; // this will increase as we go through the decimals
       int total = 0; // the number to return

       for(int i = (strlen(target) -1);i >= 0; i--) // go from end to beginning of string
       // added -1 to strlen as not to go past array bounds 
        {
            if(target[i] >= '0' && target[i] <= '9') // check character is digit
            {
                total  += ((target[i] & 0x0F )* multiple);
                // add to total, AND against 0F to get digit,
                // then multiply
                multiple *= 10; // multiply the multiple to increase
                // next number (HTU etc)

            }
        }

        return total; // return the final total, simples :D

}


Code: Select all

Output: 13370
Since I read bitmasking in one of my books a few months back, I've been hooked, so there you go ;)


EDIT: bare in mind that with simple adjustment, this would work with C-style string too, you would just use strlen() instead of .length() , actually, scratch that out, i'll stick that in the code :P
EDIT 2: the code now takes any kind of string, literal, c-style, and C++ style as long as you use c_str()


EDIT 2.5: btw, I had no problem with your solution Ginto8, I was impressed by how you did it, I've just been mulling over something like this in my head for a while now, and i'm a complete bitmask zealot :lol:
---------------------------------------------------------------------------------------
I think I can program pretty well, it's my compiler that needs convincing!
---------------------------------------------------------------------------------------
And now a joke to lighten to mood :D

I wander what programming language anakin skywalker used to program C3-PO's AI back on tatooine? my guess is Jawa :P
User avatar
Ginto8
ES Beta Backer
ES Beta Backer
Posts: 1064
Joined: Tue Jan 06, 2009 4:12 pm
Programming Language of Choice: C/C++, Java

Re: std::string-to-int converter

Post by Ginto8 »

I added a char* version.

PiP: How do you do that? teach me! ;)
Quit procrastinating and make something awesome.
Ducky wrote:Give a man some wood, he'll be warm for the night. Put him on fire and he'll be warm for the rest of his life.
Post Reply