2

I want to make a C++ method that separates an int to a char array. And gives a part of the int back.

Example:

Input:

int input = 11012013;
cout << "day = " << SeperateInt(input,0,2); << endl;
cout << "month = " << SeperateInt(input,2,2); << endl;
cout << "year = " << SeperateInt(input,4,4); << endl;

output:

day = 11
month = 01
year = 2013

I thought it was something like this. But that doesn't work for me so I wrote:

int separateInt(int input, int from, int length)
{
    //Make an array and loop so the int is in the array
    char aray[input.size()+ 1];
    for(int i = 0; i < input.size(); i ++)
        aray[i] = input[i];

    //Loop to get the right output 
    int output;
    for(int j = 0; j < aray.size(); j++)
    {
        if(j >= from && j <= from+length)
            output += aray[j];
    }

  return output;
}

But,

1) You can't call the size of the int this way.
2) You can't just like a string say i want element i of the int, because then this method is useless

How can this be solved?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Lutske
  • 117
  • 3
  • 17

3 Answers3

4
int input = 11012013;
int year = input % 1000;
input /= 10000;
int month = input % 100;
input /= 100;
int day = input;

Actually, you can create required function quite easily with integer division and modulo operator:

int Separate(int input, char from, char count)
{
    int d = 1;
    for (int i = 0; i < from; i++, d*=10);
    int m = 1;
    for (int i = 0; i < count; i++, m *= 10);

    return ((input / d) % m);
}

int main(int argc, char * argv[])
{
    printf("%d\n", Separate(26061985, 0, 4));
    printf("%d\n", Separate(26061985, 4, 2));
    printf("%d\n", Separate(26061985, 6, 2));
    getchar();
}

Result:

1985
6
26
Spook
  • 25,318
  • 18
  • 90
  • 167
1

The easiest way I can think of is formatting the int into a string and then parsing only the part of it that you want. For example, to get the day:

int input = 11012013;

ostringstream oss;
oss << input;

string s = oss.str();
s.erase(2);

istringstream iss(s);
int day;
iss >> day;

cout << "day = " << day << endl;
user1610015
  • 6,561
  • 2
  • 15
  • 18
  • Oh my, using stringstream for simple mathematical operations is like using a bazooka to kill an ant... – Spook Jan 11 '13 at 11:23
1

First convert your integer value to char string. use itoa() http://www.cplusplus.com/reference/cstdlib/itoa/

then just traverse you new char array

int input = 11012013;
char sInput[10];
itoa(input, sInput, 10);
cout << "day = " << SeperateInt(sInput,0,2)<< endl;
cout << "month = " << SeperateInt(sInput,2,2)<< endl;
cout << "year = " << SeperateInt(sInput,4,4)<< endl;

then change your SeprateInt to handle char input

use atoi() http://www.cplusplus.com/reference/cstdlib/atoi/ to convert back to integer format if required.

Lutske
  • 117
  • 3
  • 17
Arif
  • 1,601
  • 2
  • 21
  • 34