C++ changing char to int

  • LILB811
  • Born
  • Born
  • LILB811
  • Posts: 2

Post 3+ Months Ago

I know how to change a char to an int using the atoi(&variable). If I have an array of chars called num[40] and i want to take each of those chars and convert them to an array of ints called num2[40] how would I be able to do that and take each individual number?
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Couldn't you just loop through your array and convert each char to an int using atoi(&variable) ?
  • LILB811
  • Born
  • Born
  • LILB811
  • Posts: 2

Post 3+ Months Ago

I attempted to do that as well but when I ran the loop instead of taking one individual char it took everything together. When I wanted to convert char[1], i got char[1] and everything after that when I only wanted the one number.
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Can you show me the code on how you tried to do that?
  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

atoi is a function that takes a constant char pointer (char array variable) and converts the entire char array to its integer equivalent, so if you pass it the array name with a specified index, i.e. num[1], it will treat that as a pointer to the beginning of the string (char array) and keep going until it finds the null pointer. If you want to convert each individual char in the char array separately I think you will have to use casting instead.

The problem with this is that when you cast the individual chars to ints you will get their ascii table equivalents instead of a direct conversion to an integer. For instance, when you cast the character 1 to an int the result will be 49 because that is the ascii integer value of the digit 1 as opposed to the plain integer 1.

Since the ascii values of the digits 1-9 are off by 48 (0 is 48, 9 is 57), you can correct by subtracting 48 when you cast your chars to ints. This will obviously only work if the chars in question are the digits 1-9 so you might want to test for that with an if statement.

Code: [ Select ]
#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main(int argc, char *argv[])
{
 char num[] = "123456789";
 int length = strlen(num);
 int num2[length];

 for(int i=0; i<length; i++)
 {
  // cast to ints and subtract 48 to account for ascii values of digits
  num2[i] = (int)num[i] - 48;
 }
 
 for(int i=0; i<length; i++)
 {
  cout << num2[i];
 }
 system("PAUSE");    
 return 0;
}
  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. using namespace std;
  5. int main(int argc, char *argv[])
  6. {
  7.  char num[] = "123456789";
  8.  int length = strlen(num);
  9.  int num2[length];
  10.  for(int i=0; i<length; i++)
  11.  {
  12.   // cast to ints and subtract 48 to account for ascii values of digits
  13.   num2[i] = (int)num[i] - 48;
  14.  }
  15.  
  16.  for(int i=0; i<length; i++)
  17.  {
  18.   cout << num2[i];
  19.  }
  20.  system("PAUSE");    
  21.  return 0;
  22. }
  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

Upon further review, I don't think an explicit cast is even needed. I tried changing
num2[i] = (int)num[i] - 48;
to
num2[i] = num[i] - 48;
and it still works. I've been working in java for some time now where an explicit cast is needed to extract the int value of a char type, but it doesn't seem to be necessary here.
  • dr_geek
  • Beginner
  • Beginner
  • User avatar
  • Posts: 62
  • Loc: london town

Post 3+ Months Ago

the easiest, safest and most portable way is to use the standard library:
Code: [ Select ]
#include <stdlib.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>

using namespace std;

int main() {

 string num = "123456789"
 vector<int> num2;
 
 transform(num.begin(), num.end.(), num2.begin(),
  ptr_fun(atoi))

 copy(num2.begin(), num2.end(),
  ostream_iterator<int>(cout, ""));

 return 0;
}
  1. #include <stdlib.h>
  2. #include <string>
  3. #include <iostream>
  4. #include <algorithm>
  5. #include <functional>
  6. #include <vector>
  7. using namespace std;
  8. int main() {
  9.  string num = "123456789"
  10.  vector<int> num2;
  11.  
  12.  transform(num.begin(), num.end.(), num2.begin(),
  13.   ptr_fun(atoi))
  14.  copy(num2.begin(), num2.end(),
  15.   ostream_iterator<int>(cout, ""));
  16.  return 0;
  17. }
  • rmStar-Rf
  • Newbie
  • Newbie
  • rmStar-Rf
  • Posts: 5
  • Loc: Philippines

Post 3+ Months Ago

i don't think it works. i tried to compile it using g++, it seem not to see the transform() function. that is after some minor syntax corrections (semicolon).
  • rmStar-Rf
  • Newbie
  • Newbie
  • rmStar-Rf
  • Posts: 5
  • Loc: Philippines

Post 3+ Months Ago

I have figured out what is faulty with the atoi... please see the code below.

Code: [ Select ]
/**
* charConvert.cpp
* rmStar-Rf
*
* */

#include <iostream>
#include <cstdlib>
using namespace std;

int main( void )
{
    char num[ 10 ] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };

    int num2[ 10 ];

    char aa; //needed as a temporary variable.
    for( int ii = 0; ii < 10; ii++ ){
        aa = num[ ii ]; //trick here!!
        num2[ ii ] = atoi( &aa ); //then here!!
    }

    cout << "integers (dyaraaaan!): ";
    for( int ii = 0; ii < 10; ii++ ){
        cout << num2[ ii ] << ", ";
    }
    cout << endl;

    return 0;
}
  1. /**
  2. * charConvert.cpp
  3. * rmStar-Rf
  4. *
  5. * */
  6. #include <iostream>
  7. #include <cstdlib>
  8. using namespace std;
  9. int main( void )
  10. {
  11.     char num[ 10 ] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
  12.     int num2[ 10 ];
  13.     char aa; //needed as a temporary variable.
  14.     for( int ii = 0; ii < 10; ii++ ){
  15.         aa = num[ ii ]; //trick here!!
  16.         num2[ ii ] = atoi( &aa ); //then here!!
  17.     }
  18.     cout << "integers (dyaraaaan!): ";
  19.     for( int ii = 0; ii < 10; ii++ ){
  20.         cout << num2[ ii ] << ", ";
  21.     }
  22.     cout << endl;
  23.     return 0;
  24. }


atoi() seems to only see the location pointed to by the first element of the char variable ( atoi is defined to be atoi( char * ) ). So, by using num2[ ii ] = atoi( &( num[ ii ] ) ), it will always locate the ii-th element as the first character of the integer so displaying an output as:

1234567890, 234567890, and so on..

By utilizing a temporary variable aa above, the problem is solved!

I hope this solves the original problem. I believe dr_geek has a good point. since you are using C++ anyway, why don't you use #include <string> for your character arrays?

its so easy to manipulate strings since you have:
string mySstring = "1";
myString = myString + "2341";

and so on.. ;)

later on, if you need a character array representation, you can have
char aa = myString.c_str()[ 0 ];
as the first element...

good luck!

[/code]
  • m3kw
  • Born
  • Born
  • m3kw
  • Posts: 1

Post 3+ Months Ago

In case you're still wondering the question. just go

int Temp = *(int *)(num + yourAddress);

so if you have num[0 to 4 as 0xaa, 0xbb, 0xcc, 0xdd.

then Temp will be 0xaabbccdd; as integer.
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6252
  • Loc: Seattle, WA

Post 3+ Months Ago

This question was asked 8 years ago. I'm sure they've moved on.

Post Information

  • Total Posts in this topic: 11 posts
  • Users browsing this forum: No registered users and 137 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.