在c中将内容从一个数组复制到另一个数组

标签 c arrays

这里是我的程序到目前为止应该做的事情的概述。

虽然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/

相关文章:

c - 大批。访问 0xFFFFFFFF 元素

java - 理解Java中字节的掩码

c++ - C++ 中的整数数组列表<>?

php - 如何根据字母变体数组获取所有相似的字符串

ios - 无法推断通用参数 'D'。 [订单错误]

c - 如何让 ROP 小工具让 shell 工作?

c - 请任何人检查我的代码看看有什么问题

c - 初始化后的 glfw 段错误

c - struct node**hashTable 和 struct node*hashTable[MAXSIZE] 之间有什么区别?

c - 如何将指针数组引用到多个常量数组