【发布时间】:2023-03-05 03:34:02
【问题描述】:
我正在为汇编程序编写编译器,我需要对从文件中获取的文本进行解析,而不对原始字符串进行任何更改。我用来复制字符串的函数是strcpy到缓冲区,剪切字符串的函数是strtok剪切缓冲区。
一切都很完美,但是一旦我在使用函数 addressingConstantIndex 后尝试剪切原始字符串,我就会得到 null。
我试图将缓冲区的类型更改为字符指针,但它并没有真正起作用。我猜主要问题在于我将原始字符串复制到缓冲区的方式。
int main(){
char desti[MAXCHAR];
char *temp;
char *token;
temp = "mov LIST[5] , r4";
strcpy(desti,temp);
printf("\ndest is : %s\n", desti);
token = strtok(desti," ");
printf("\nthe Token in Main is : %s \n", token);
token = strtok(NULL, ",");
printf("\nthe Token in Main is : %s\n", token);
printf("\nThe value is %d \n ",addressingConstantIndex(token));
token = strtok(NULL, " ,");
printf("\nthe Token in Main is : %s\n", token);
return 0;
}
int addressingConstantIndex(char * str) {
char buf[43];
char *token;
int ans;
strcpy(buf, str);
token = strtok(buf, "[");
printf("The string is %s\n",str);
if (token != NULL)
{
printf("the token is %s\n", token);
token = strtok(NULL, "]");
printf("the token is %s\n", token);
if(isOnlyNumber(token))
{
token = strtok(NULL, " ");
if (checkIfSpaces(token,0) == ERROR)
{
printf("ERROR: Extra characters after last bracket %s \n", str);
ans = ERROR;
} else
ans = OK;
} else {
printf("ERROR: Unknown string - %s - its not a macro & not a number.\n", token);
ans = ERROR;
}
} else {
printf("ERROR: %s , its not a LABEL", token);
ans = ERROR;
}
return ans;
}
int isOnlyNumber(char *str) {
int i, isNumber;
i = 0;
isNumber = 1;
if (!isdigit(str[i]) && !(str[i] == '-' || str[i] == '+'))
{
isNumber = ERROR;
}
i++;
while (i < strlen(str) && isNumber == 1)
{
if (!(isdigit(str[i]))) {
if (isspace(str[i]))
isNumber = checkIfSpaces(str, i);
else
isNumber = ERROR;
}
i++;
}
return isNumber;
}
int checkIfSpaces(char *str, int index) {
int i;
if (str == NULL)
{
return OK;
} else {
for (i = index; i < strlen(str); i++)
{
if (!isspace(str[i])) return ERROR;
}
}
return OK;
}
预期结果:
dest is : mov LIST[5] , r4
the Token in Main is : mov
the Token in Main is : LIST[5]
The string is LIST[5]
the token is LIST
the token is 5
The value is 1
the Token in Main is : r4
真实结果:
dest is : mov LIST[5] , r4
the Token in Main is : mov
the Token in Main is : LIST[5]
The string is LIST[5]
the token is LIST
the token is 5
The value is 1
the Token in Main is : (null)
区别在结果的最后一行。
【问题讨论】:
-
如果您需要保留原始字符串,请复制该字符串并在副本上使用
strtok(),或者不要使用strtok()。 -
另请注意,您不能使用
strtok()同时分析两个不同的字符串。基本上,strtok()通常是错误的函数使用;这是错误功能的许多次之一。请改用strspn()和strcspn()。 -
我需要对我得到的字符串的每个部分做一些验证。
-
你的平台有
strtok_r吗?