我编写代码来查找(单引号或双引号)引号,一系列字符或“|”的开头和结尾然后将这些值放入数组中。出于某种原因,我不断遇到段错误。此外,之后,如何显示表格以确定它是否正常工作?
int parsing(const char *commandline, int array[])
{
int number= 0;
int index = 0;
while(commandline[index]!= '\0'){
/* when you have spaces*/
if (isspace(commandline[index]))
index++;
/* when you have double quotes*/
if(commandline[index] == '"'){
printf("running");
array[number] = index;
number++;
index++;
while(commandline[index] != '"' || '\0')
index++;
if(commandline[index] == '\0')
return printf("ERROR: Quote not ended");
array[number]= index;
number++;
}
/* when you have single quotes*/
if(commandline[index] == '\''){
array[number] = index;
number++;
index++;
while(commandline[index] != '\'' || '\0')
index++;
if(commandline[index] == '\0')
return printf("ERROR: Quote not ended");
array[number]= index;
number++;
}
/* when you have |*/
if ( commandline[index] == '|')
{
array[number] = index;
number++;
}
/* when you have only letters*/
if(isalnum(commandline[index])){
array[number] = index;
index++;
number++;
while (isalnum(commandline[index]))
index++;
array[number] = index;
}
}
return *array;
}
编辑:添加错误检查
答案 0 :(得分:0)
我找到了许多需要改进的地方,并将其添加为评论:
int parsing(const char *commandline, int array[])
{
int number= 0;
int index = 0;
while(commandline[index]!= '\0'){
/* when you have spaces*/
if (isspace(commandline[index])) {
index++;
continue; // So that if you are at the end of the string
// you don't segfault.
}
/* when you have double quotes*/
if(commandline[index] == '"'){
printf("running");
array[number] = index;
number++;
index++;
// || '\0' just does nothing. Do:
while(commandline[index] != '"') {
if(commandline[index] == '\0') {
// returning printf sounds silly. printf returns the number
// of character written.
// Also: Add \n to your printf.
printf("ERROR: Quote not ended\n");
return -1;
}
index++;
}
array[number]= index;
number++;
index++;
continue; // Same as for when you have spaces.
}
/* when you have single quotes*/
if(commandline[index] == '\''){
array[number] = index;
number++;
index++;
// Ditto there.
while(commandline[index] != '\'') {
if(commandline[index] == '\0') {
printf("ERROR: Quote not ended\n");
return -1;
}
index++;
}
array[number]= index;
number++;
index++;
continue; // here also.
}
/* when you have |*/
if ( commandline[index] == '|')
{
array[number] = index;
number++;
index++; // move to next character.
continue;
}
/* when you have only letters*/
if(isalnum(commandline[index])){
array[number] = index;
index++;
number++;
while (isalnum(commandline[index]))
index++;
array[number] = index;
continue;
}
// And if you get here, you have neigher an alphanum nor a | nor a "
// nor a ', what do you want to do ?
index++;
continue;
}
return *array;
}