簡體   English   中英

如何獲取特定的數組元素

[英]How to take a particular array element

我已經聲明了char數組char BCommand[100]="00LI002LE99" ,我只想使用00299

這是我嘗試過的代碼:

 char Lcommand[3],Lecommand[3];
 unsigned char SlaveNodeID=0,NodeValue=0,ChSum2=0;
 Lcommand[0]=BCommand[4];
 Lcommand[1]=BCommand[5];
 Lcommand[2]=BCommand[6];
 Lecommand[0]=BCommand[9];
 Lecommand[1]=BCommand[10];
 SlaveNodeID = atoi(Lcommand);
 NodeValue = atoi(Lecommand);

有什么有效的方法嗎?

我認為您需要int值,如果您想要00299整數值,可以使用此值。

int SlaveNodeID = (BCommand[4] - '0') * 100 + (BCommand[5]-'0') * 10 + (BCommand[6] - '0');
int NodeValue   = (BCommand[5] - '0') * 10  + (BCommand[6]-'0');  

printf("%3d",SlaveNodeID);
printf("%2d",NodeValue);

如果要將它們分成字符串,則聲明大小為4和3的字符數組。使用sprintf()snprintf()代替printf()

您可以使用string.h [1]庫來處理字符數組。

在這里,您可以找到諸如strncpy [2]之類的函數,因此您編寫的代碼將類似於:

 char Lcommand[3],Lecommand[3];
 unsigned char SlaveNodeID=0,NodeValue=0,ChSum2=0;
 strncpy(Lcommand, Bcommand+2, 3);
 strcpy(Lecommand, Bcommand+7, 3);
 SlaveNodeID = atoi(Lcommand);
 NodeValue = atoi(Lecommand);

另外,我建議您查看string.h中的其他函數,因為它們可能會對您有所幫助。

[1] -http://www.cplusplus.com/reference/cstring/?kw=string.h

[2] -http://www.cplusplus.com/reference/cstring/strncpy/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM