2013-01-11 35 views
2

我想制作一个C++方法,将int分配给一个char数组。 并给出了int的一部分。C + +分隔INT到字符数组

例子:

输入:

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

输出:

day = 11 
month = 01 
year = 2013 

我还以为是像this。但是,这并不为我工作,所以我写了:

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; 
} 

但是,

)您不能调用INT的大小这样。
)你不能只是像一个字符串说,我想为int i个元素,因为那么这种方法是没有用的

因此,没有人知道这可怎么解决呢?感谢您的帮助:)

+1

'input.size()'其中'input'是'int' !!! – Nawaz

+0

[在int数组中存储一个int的可能的重复?](http://stackoverflow.com/questions/1522994/store-an-int-in-a-char-array) – moooeeeep

+0

你确定你的输入是int不是字符串? – qPCR4vir

回答

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

其实,你可以很容易地创建所需的功能与整数除法和模运算符:

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(); 
} 

结果:

1985 
6 
26 
+0

感谢:D它的工作 – Lutske

1

我能想到的最简单的方法是将int格式化为字符串,然后仅解析所需的部分。例如,为了得到天:

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; 
+0

哦,我的,使用stringstream进行简单的数学运算就像使用火箭筒杀死一只蚂蚁一样... – Spook

1

首先将你的整数值转换为char字符串。使用itoa()http://www.cplusplus.com/reference/cstdlib/itoa/

然后就遍历你新的字符数组

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; 

然后改变你的SeprateInt处理字符输入

使用atoi()http://www.cplusplus.com/reference/cstdlib/atoi/ 如果需要转换回整数格式。

+0

你想在cInput中停止什么? – Lutske

+0

它拼错了,它是'sInput'而不是'cInput' – Arif

+0

在这里你不能计算输入的长度。因为它是由字符char – Lutske