我正在寫一段代碼在C++中,需要一個字符數組作爲輸入,其中包含類似JSON的文本。這個想法是從該JSON獲取值。C++雖然循環奇怪的行爲
那是給錯誤的功能如下:
variable * getVariableInfo(const char * variableInfo){
/*get {...}*/
printf("%s\n",variableInfo);
int start, countWord=0;
int order=-1, type=-1;
char * value;
variable * returnValue;
const char * aux;
while(*(variableInfo++)){
if(*variableInfo=='"'){
variableInfo++;
aux=variableInfo;
countWord=0;
while(*(variableInfo++)!='"'){
countWord++;
}
char *word = (char *) calloc(1, sizeof(char) * (countWord + 1));
strncpy(word, aux, countWord);
word[countWord]='\0';
printf("\nWORD %s", word);
while(*(variableInfo++)!='"');
aux=variableInfo;
countWord=0;
while(*(variableInfo++)!='"'){
countWord++;
}
char *str = (char *) calloc(1, sizeof(char) * (countWord + 1));
strncpy(str, aux, countWord);
str[countWord]='\0';
printf("\nSTR %s\n",str);
if(strcmp(word,ORDER)==0){
order=a2i(str);
printf("ORDER = %i", order);
}
/*TYPE*/
else if(strcmp(word,TYPE)==0){
if(strcmp(str, valueINT)==0) type=TYPE_INT;
else if(strcmp(str, valueSTR)==0) type=TYPE_STRING;
else if(strcmp(str, valueBOOL)==0) type=TYPE_BOOLEAN;
else return 0;
printf("TYPE = %i", type);
/*VALUE*/
}
else if(strcmp(word,VALUE)==0){
value = (char *) calloc(1, sizeof(char) * (countWord + 1));
strncpy(value, str, countWord);
value[countWord]='\0';
printf("VALUE = %s", value);
}
else{
printf("ELSE");
return 0;
}
}
printf("\nCHAR %c\n---------", *variableInfo);
}
printf("Pass");
if(type==-1||order==-1||!value){
if(!type) printf("NOT");
if(!order) printf("NOO");
if(!value) printf("NOV");
return 0;
}
returnValue = (variable *) calloc(1,sizeof(variable)+(sizeof(char)*(strlen(value)+1)));
returnValue->order=order;
returnValue->type=type;
strncpy(returnValue->value,value,strlen(value));
returnValue->value[strlen(value)]='\0';
return returnValue;
}
的VAR「variableInfo」是從另一個函數發送,就像是從哪個包含原始完整JSON類文本的輔助指針下面創建:
variableInfo = (char *) calloc(1, sizeof(char) * (countWord + 1));
strncpy(variableInfo, aux, countWord);
variableInfo[countWord]='\0';
variables[variableCount]=getVariableInfo(variableInfo);
正如你所看到的,我加了一些printf和輸出如下所示:
{"ORDER":"0","TYPE":"int","VALUE":"9999"}
WORD ORDER
STR 0
ORDER = 0
CHAR ,
---------
WORD TYPE
STR int
TYPE = 0
CHAR ,
---------
WORD VALUE
STR 9999
VALUE = 9999
CHAR }
---------
CHAR
Segmentation fault (core dumped)
我打印「variableInfo」變量,它顯示文本的右側一塊應該被髮送到「getVariableInfo」功能,那麼對於訂單,類型和值的值正確地從JSON,像文本拍攝。但是,自上一輪以來,即使最後一個字符爲'\ 0',它仍然保留在while循環中(請參見輸出「CHAR}」應該是最後一次,而下一次檢查while聲明它應該結束它,但它然後打印「CHAR」)。
感謝您的幫助。
親切的問候。
與您的問題完全無關,但那是遍歷json字符串的很多代碼。如果可能的話,考慮以不同的方式來做到這一點。 – Ezio
這看起來更像C而不是C++ – nefas
*但是,我得到了分段錯誤錯誤,* - 並不感到驚訝,所有的「C」代碼。'std :: string'和'std :: vector'的用法在哪裏?如果它是JSON,請考慮使用JSON庫,而不要嘗試自己分析此代碼。 – PaulMcKenzie