c - 将 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');
解决方案
根据您的描述,您想从作为字符串存储/提供的列表中提取数字,例如“(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);
推荐阅读
- java - 如何在java项目中使用省略库
- angular - 加载 Angular7 应用程序需要很长时间
- nginx - 我的 nginx 配置可以在没有默认服务器的情况下工作吗
- deep-learning - 如何手动计算像 ResNet 这样的 CNN 的后向传递中的 FLOPS 数?
- apache - 有没有办法在同一台机器上同时运行 Apache 和 IIS
- python - 如何在多级字典中查找值
- apache - RewriteOptions InheritBefore 的 Htaccess 问题
- azure - Azure Function App 中的路由或多个函数
- python - 如何使用 flask_sqlalchemy 从 MySQL 获取 varchar 类型的数据?
- python-3.x - slackAPI python在烧瓶中使用Jinja在父消息问题下传播消息回复