首页 > 解决方案 > 将 char 数组从消息队列转换为 int 数组

问题描述

所以我从消息队列中得到一条消息,它应该如下所示: (3 2 1) 我需要转换这 3 个元素并存储在一个整数数组中。

do
{
  if(message.mesg_text[x]!=' ')
  {
    asd[j]=(int)message.mesg_text[x]-48;
    x++;
  }
  else
  {
    j++;
    x++;
  }
}while(message.mesg_text!='\0');

标签: c

解决方案


根据您的描述,您想从作为字符串存储/提供的列表中提取数字,例如“(1 2 3)”。

请注意,C 提供 atoi(3) 将整数的字符串表示形式转换为 int 类型。另请注意,C 提供了 ctype.h,它提供了 isdigit() 和 isspace() 来确定字符是数字还是空格。可以通过跳过空格来去除多余的空格...

#include <ctype.h>
#include <string.h>
#include <strtok.h>

int
list_extract_ints(char* msg, int asd[], int capacity) {
    // weakest precondition(s):
    // message needs to be valid string
    if( ! msg ) { return 0; }
    if( capacity <= 0 ) { return 0; }

    int count = 0;
    char* p = msg;

    int len = strlen(p);
    // skip leading space
    for( ; *p && isspace(*p); ) { p++; }
    // strip trailing blanks?
    // skip '('
    if( '(' == *p ) { p++; }
    char ptoken = strtok(p," ");
    // do you allow '+' or '-'?
    if( ptoken && isdigit(*ptoken) ) {
        // may want to skip spaces here...
        asd[count++] = atoi(ptoken);
    }
    // gather ints until capacity reached, or list end
    for( ; (count<capacity) && (ptoken = strtok(NULL, " )")); ) {
        // may want to skip spaces here...
        if( ptoken && isdigit(*ptoken) ) {
            asd[count++] = atoi(ptoken);
        }
    }
    return count;
}

然后你调用这个列表提取函数,

...
int asd[capacity];
int count = list_extract_ints(message.mesg_text, asd, capacity);

推荐阅读