Jump to content

Convert char array to int (c++)

MisterWhite

i know i can convert this:

char myChar[] = "125697"

to ant integer

but will something like this work?:

char myChar [] = "125    "

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to comment
Share on other sites

Link to post
Share on other sites

Im new to C++ but i think it may work due to logic.

AMD FX-8350|8GB DDR3|GTX750TI|2TB HDD|CX-430 PSU|

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

What exactly do you mean by convert?

Like turn the string "125     " into a number?
Or reinterpret the data as integers?
 

Converting to a number can simply be done using atoi: 

int value = atoi(cString);

To reinterpret cast you can do one of the following:

const int* array = (int*)cString;

It would be nice if you could explain what your question is a bit more!

Link to comment
Share on other sites

Link to post
Share on other sites

 

i know i can convert this:

char myChar[] = "125697"

to ant integer

but will something like this work?:

char myChar [] = "125    "

For the first example, do you mean getting an integer with the value 125697 , from a character array holding "125697"?

 

Since C++11 , we've had std::stoi() , which takes as a parameter an std::string. If you still want to use cstrings , then there's atoi().

 

Or you can make your own function :

// c - pointer to a null-terminated arrayint atoi(char *c){int i = 0,s=0;//while we are still in the memory assigned to the arraywhile(c[i]!='\0'){//If the character we are currently  looking at is a numberif(c[i] >= 48 && c[i] <= 57) s = s*10 + c[i] - 48;//Next character in the arrayi++;}//Return the numberreturn s;}

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

 

 

yeah, i've learned about atoi(), my question was that if there are spaces after the number, will it convert properly, and it does, so it is answered :P

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×