【问题标题】:C++ separate int in to char array [closed]C ++将int分离到char数组中[关闭]
【发布时间】:2012-12-25 23:05:00
【问题描述】:

我想创建一个将 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

我认为它类似于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;
}

但是,

1) 你不能用这种方式调用 int 的大小。
2) 你不能像一个字符串一样说我想要元素 i int的,因为那样的话这个方法就没用了

如何解决?

【问题讨论】:

标签: c++ arrays char int


【解决方案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;

【讨论】:

  • 天哪,使用 stringstream 进行简单的数学运算就像使用火箭筒杀死一只蚂蚁......
【解决方案2】:
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

【讨论】:

    【解决方案3】:

    首先将您的整数值转换为 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/ 如果需要,转换回整数格式。

    【讨论】:

    • 你想在 cInput 中停止什么?
    • 拼写错误,是sInput 而不是cInput
    • 这里不能计算输入的长度,方法内部。因为它是逐字符的
    • itoa() 返回 null 终止的字符串。看看cplusplus.com/reference/cstdlib/itoa
    猜你喜欢
    • 1970-01-01
    • 2023-02-22
    • 2014-11-30
    • 2013-06-12
    • 2016-03-07
    • 2015-01-04
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多