2

int を char 配列に分離する 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

こんなものかと思っ。しかし、それは私にはうまくいかないので、私は書きました:

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

しかし、

1 ) この方法で int のサイズを呼び出すことはできません。
2)文字列のように、intの要素iが必要だと言うことはできません。その場合、このメソッドは役に立たないためです

これはどのように解決できますか?

4

3 に答える 3

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
于 2013-01-11T11:22:54.610 に答える
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;
于 2013-01-11T11:19:45.160 に答える
1

まず、整数値を char 文字列に変換します。http://www.cplusplus.com/reference/cstdlib/itoa/を使用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;

次に、SeprateIntchar入力を処理するように変更します

atoi() 必要に応じてhttp://www.cplusplus.com/reference/cstdlib/atoi/を使用 して整数形式に変換します。

于 2013-01-11T11:23:41.290 に答える