这里是我的程序到目前为止应该做的事情的概述。
虽然inputLine
中有更多单词:
- 从
inputLine
中获取下一个单词 - 如果下一个单词适合
inputline2
- 将下一个单词添加到
inputline2
(不起作用,可能不需要) - 将
inputline2
添加到outputBuffer
(不起作用) - 格式
输出缓冲区
- 将下一个单词添加到
否则:
- 将
outputBuffer
写入输出文件 - 清空
outputBuffer
(将\0放在位置0)
无论我如何尝试,outputline2
和/或 outputBuffer
都无法正确复制 inputline
的内容。我拥有 inputline2
的唯一原因是因为我最初使用 fgets
并将文本文件中一行的内容放入 inputline
中。然而,由于我的数组长度假设为 40,它总是会将原始行中的一些单词切成两半。如果可以以某种方式避免这种情况,我什至不需要 inputline2
。无论哪种方式,在这两种情况下,word 中的内容(只是原始inputline
中的一个单词)都无法正确复制。
void format(FILE *ipf, FILE *outf)
{
char inputline[80];
char outputBuffer[MaxOutputLine];
char word[MaxOutputLine];
while(fgets(inputline, 80, ipf) != NULL)
{
int pos = 0;
int i;
int j = 0;
char inputline2[MaxOutputLine] = {'\0'};
while(pos != -1)
{
i=0;
pos = nextword(inputline, word, pos);
if(strlen(word) <= (40 - strlen(inputline2)))
{
while(i < strlen(word))
{
inputline2[j] = word[i];
i++;
j++;
}
j++;
printf("%s", inputline2);
}
}
}
}
最佳答案
int nextword(char *inputline, char *word, int pos1) //takes a word beginning from pos and puts it in word and re\
turns the new position of beginning of the next word
{
int pos2 = 0;
if(inputline[pos1] == '\0')
{
return -1;
}
if(inputline[pos1] == ' ')
{
while(inputline[pos1] == ' ')
{
pos1++;
}
}
else
{
while(inputline[pos1] != ' ' && inputline[pos1] != '\n' && inputline[pos1] != '\0')
{
word[pos2] = inputline[pos1];
pos1++;
pos2++;
}
if(pos1 == '\n' || pos1 == '\0')
{
return -1;
}
pos1++;
}
word[pos2]='\0';
return pos1;
}
关于在c中将内容从一个数组复制到另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32832596/