Convert a string to an integer

luxo-JR

Member
Hello, I need your lights... For my development I need a function which converts a string to an integer, example this string "1234" gives this integer 1234. I was inspired by the function of the C language, atoi (alpha to integer). But the string processing functionalities are different from GML. I made several unsuccessful attempts. I attach the code of atoi (simplified) for inspiration ... Thank you in advance.

Code:
int atoi(char s[])
{
    int i, n;
    n = 0;
    for(i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
    {
        n = 10 * n + (s[i] - '0');
    }

    return(n);
}
 
Code:
int atoi(char s[])
{
    int i, n;
    n = 0;
    for(i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
    {
        n = 10 * n + (s[i] - '0');
    }

    return(n);
}
Woooo, man, relax! šŸ˜‚
How 'bout
GML:
//Hardcoded version
var _my_int = real("1234");

//or pass in a variable
var _str = "1234";
var _my_int = real(_str);
 

luxo-JR

Member
Thanks, I had already looked at the GML documentation. I will be satisfied with real ("..."). I'm still thinking of rewriting the atoi function in GML, just in principle ...
 

luxo-JR

Member
I need help. I am submitting this code to you because there is a problem and I do not see it. When I run it, I pass the character '1' twice. My example string is '123'.
First loop round, index: 0, character: '1'
Second loop round, index: 1, character '1', which is not normal
Third loop round, index: 2, character: '2', which is not normal
And there is a fourth loop round, index: 3, character: '3', which is not normal ... ??? An idea ???

GML:
    var str = "123";
    var i = 0;
    var n = 0;
    
    while (string_ord_at(str, i) >= ord("0")) && (string_ord_at(str, i) <= ord("9"))
    {
        n = 10 * n + (string_ord_at(str, i) - ord("0"));
        show_message("> indice : " + string(i) + " ! char : " +  string_char_at(str,i));
        i++;
    }
 

gkri

Member
Screenshot 2021-06-09 113152.png
I think you should start with index 1 instead of 0. I have not tried your code but my guess is this:

GML:
//var i = 0;

var i = 1;
 
Top