我创建了一个程序,该程序应该完全证明输入到类中的文本,除了将单词传输到输出时,会显示错误,我不确定为什么,但它最终会在运行程序时导致分段错误。是什么导致了这个错误,我该如何解决这个问题?
void format_text(int * option_stats, unsigned width, char * text)
{
int x = 0, y = 0, spaces = 0, remain = 0, j = 0;
char* words, output;
char temp[200] = {" "};
words = strtok(text, " ");
while (words != NULL)
{
if (y + strlen(words) < width)
{
strcpy(temp, words);
strcat(temp, " ");
y += strlen(words) +1;
spaces += 1;
words = strtok(NULL, " ");
}
else if(y + strlen(words) == width)
{
strcpy(temp, words);
printf("%s\n", temp);
y = 0;
spaces = 0;
}
else if(spaces > 1)
{
remain = width - (y - 1);
j = remain % (spaces - 1);
remain = (remain-j)/(spaces-1);
output = strtok(temp, " ");
while (output != NULL)
{
printf("%c", output);
if(j > 0)
{
printf(" ");
j--;
}
output = strtok(NULL, " ");
y = 0;
spaces = 0;
words = strtok(NULL, " ");
}
}
x += (strlen(words) + 1);
}
}