C 将字符数组从消息队列转换为int数组
所以我从消息队列中得到一条消息,它应该是这样的,例如:(3 2 1) 我需要转换这个3元素并存储在整数数组中C 将字符数组从消息队列转换为int数组,c,C,所以我从消息队列中得到一条消息,它应该是这样的,例如:(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'); 根据您的描述,您希望从存储/提供为字符串的列表中提取数字,例如“(
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)来将INTEGER的字符串表示形式转换为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;
}
asd[j]=(int)message.mesg_text[x]代码>->asd[j]=message.mesg_text[x]-“0”代码>可能。它不起作用。它可以很好地转换前2个,但在最后一个,我在if
块中得到负值,在else
中增加j
。但是,我认为情况正好相反。您想要if
部分中的j++
,而不是else
部分谢谢:解决了。很高兴修复了它。但是,您的第二次编辑似乎在
时破坏了。比如:while(j<3){int chr=message.mesg_text[x++];if(chr==0)break;if(chr!='')asd[j++]=chr-'0';}
...
int asd[capacity];
int count = list_extract_ints(message.mesg_text, asd, capacity);