Better way to do this?

This is a discussion on Better way to do this? within the C++ Programming forums, part of the General Programming Boards category; Is there some method to combine all these steps? Code: char char2num[10]; char2num[0] = '0'; char2num[1] = '1'; char2num[2] = ...

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    21

    Better way to do this?

    Is there some method to combine all these steps?

    Code:
    char char2num[10];
    
    char2num[0] = '0';
    char2num[1] = '1';
    char2num[2] = '2';
    char2num[3] = '3';
    char2num[4] = '4';
    char2num[5] = '5';
    char2num[6] = '6';
    char2num[7] = '7';
    char2num[8] = '8';
    char2num[9] = '9';

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Code:
    char char2num[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Code:
    char char2num[] = "0123456789";
    That's not exactly the same, but null termination is generally useful.
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Jun 2002
    Posts
    230
    Use a for loop to assign the values into the array. For the chars you could increment by number and then convert the number into a char. I forgot the function for that. Someone here would know.
    C++ Rules!!!!
    ------------
    Microsoft Visual Studio .NET Enterprise

  5. #5
    Registered User
    Join Date
    Sep 2005
    Posts
    21
    Thanks for the quick replies
    Works great now!

  6. #6
    Registered User
    Join Date
    May 2006
    Posts
    903
    There are many ways:
    Code:
    char whatever[10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    char whatever[] = "0123456789";
    
    char whatever[10] = {0};
    for(int i = 0; i < 10; i++)
        whatever[i] = i + '0';
    
    char whatever[10] = {0};
    for(char c = '0'; c <= '9'; c++)
        whatever[c - '0'] = c;
    
    // And so on..

Popular pages Recent additions subscribe to a feed

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