Storing a number in an array

This is a discussion on Storing a number in an array within the C++ Programming forums, part of the General Programming Boards category; Is there a fast way to store a number in an array like: Input: 234586349 becomes Code: int array[] = ...

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    7

    Storing a number in an array

    Is there a fast way to store a number in an array like:

    Input: 234586349

    becomes

    Code:
    int array[] = {2,3,4,5,8,6,3,4,9}

    Right now my method is very tricky :/

    To get the 6, I have to do:

    Code:
    int a= 234586349 / static_cast<int>(pow(10.0,3));                         // gives 234586
    int b = (234586349 / static_cast<int>(pow(10.0,4))) * 10;              // gives 234580
    
    int x = a-b;       // gives 6
    Then somehow I have to use a FOR function to get all the digits... is there a better way?
    (Preferably one that doesn't involve floating numbers and static_casts I always get into trouble around them >_<)

    Thanks!
    Last edited by C++ student; 09-28-2009 at 07:12 AM.

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    242
    Well, input is originally a string anyway, so I'd declare the input variable as a string. Then, if your array has to be an array of integers, you can convert your string digit by digit (just make sure you actually get the number you want rather than the ASCII code for the number character) for input into your array.

  3. #3
    Registered User
    Join Date
    Jun 2002
    Posts
    230
    Code:
    #include <iostream>
    #include <sstream>
    using namespace std;
    
    inline int cToInt(const string& s){
    	istringstream i(s);
    	int x;
    	i >> x
    	return x;
    }
    
    int main(){
    	string  x = "123456789";
    	int array[9];
    	
    	for(int i = 0; i < 9; i++){
    		array[i] = cToInt(x.substr(i, 1));
    		cout << array[i] << " ";
    	}
    }
    C++ Rules!!!!
    ------------
    Microsoft Visual Studio .NET Enterprise

  4. #4
    Registered User
    Join Date
    Sep 2009
    Posts
    7
    Thanks aisthesis, and gamer4life687 for the code!
    I'm new to a lot of these functions but I'll research them

  5. #5
    Registered User
    Join Date
    Jun 2002
    Posts
    230
    C++ Rules!!!!
    ------------
    Microsoft Visual Studio .NET Enterprise

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 02-22-2009, 04:17 PM
  2. convert 32 bit number to array of digits
    By droseman in forum C Programming
    Replies: 11
    Last Post: 02-18-2009, 08:37 AM
  3. Replies: 2
    Last Post: 02-08-2009, 08:26 PM
  4. help with a source code..
    By venom424 in forum C++ Programming
    Replies: 8
    Last Post: 05-21-2004, 12:42 PM
  5. Array Program
    By emmx in forum C Programming
    Replies: 3
    Last Post: 08-31-2003, 12:44 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21