简体   繁体   English

C-具有混合数字的整数数组

[英]C - Int Array to Integer with Mixed Digit Numbers

I need to convert an integer array of size 4 into an int . 我需要将大小为4的整数数组转换为int I've seen solutions for int arrays that look like {1, 2, 3, 4} turn into 1234, and I've also seen ones where an array like {10, 20, 30} would turn into 102030. However, my problem is that I'll have an array that might look like {0, 6, 88, 54} and the solutions I previously mentioned only work on arrays with int s of the same type {eg all one digit or all two digit}. 我已经看到过将{1,2,3,4}转换为1234的int数组的解决方案,并且还看到了将{10,20,30}转换为102030的int数组的解决方案。问题是我将拥有一个看起来像{0、6、88、54}的数组,而我前面提到的解决方案仅适用于具有相同类型(例如,全部一位或全部两位数字)的int的数组。

What should I do to solve this? 我该怎么做才能解决这个问题?

My expected output from the {0, 6, 88, 54} array would be 68854. {0,6,88,54}数组的预期输出为68854。


Examples An output with zeros in the middle should keep them, ie {6, 0, 0, 8} would be 6008 but {0, 6, 0, 0, 8} by default would still be 6008 in int form. 示例中间带有零的输出应保留它们,即{6,0,0,8}为6008,但默认情况下,{0,6,0,0,8}在int形式下仍为6008 I need this in an int but I wouldn't mind having a string intermediate. 我在int需要这个,但我不介意使用字符串中间。

You could do something like this: 您可以执行以下操作:

int res = 0;
int nums[4] = {1, 4, 3, 2}

int i = 0, temp;
for (i = 0; i < 4; ++i) {
  temp = nums[i];
  do {
    res *= 10;
  } while ((temp /= 10) > 0);


  res += nums[i];
}

a neat solution would perhaps be to print to a string then convert the string back to an integer 一个整洁的解决方案可能是打印到字符串然后将字符串转换回整数

char dummy[100];
int answer;
int input[4];

....

sprintf(dummy,"%d%d%d%d",input[0],input[1],input[2],input[3]);
answer=atoi(dummy);

the sprintf prints your integers into a string sprintf将您的整数打印成字符串

the atoi converts the string into your integer, and it should be able to handle a 0 at the front. atoi将字符串转换为整数,并且应该能够在前面处理0

full program 完整程序

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char dummy[100];
  int answer;
  int input[4]={3,4,0,345};

  sprintf(dummy,"%d%d%d%d",input[0],input[1],input[2],input[3]);
  answer=atoi(dummy);

  printf("%d\n",answer);

  return 0;
}

What about this solution? 那这个解决方案呢?

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int arr[] = {0, 6, 88, 54};

    char buffer[1000] = { 0 };

    for(size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
        sprintf(buffer, "%s%d", buffer, arr[i]);

    int val = strtol(buffer, NULL, 10);
    printf("%d\n", val);

    return 0;
}

int prints 608854 . int打印608854

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM