2013-01-11 36 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