【问题标题】:C programming, reading from a file and loading into an arrayC 编程,从文件中读取并加载到数组中
【发布时间】:2014-04-29 17:31:50
【问题描述】:

在打印出我读入数组的文件后,我得到了一些额外的垃圾字符。

这是我的代码

fp = fopen("load.txt", "r");

if (fp == NULL)
{
    perror("Exiting, an error occured while opening\n");
    exit(EXIT_FAILURE);
}


while((ch = fgetc(fp)) != EOF)
{
    load[i++] = ch;

}

fclose(fp);

for(i = 0; i < 100; ++i)
{

    printf("%c", load[i]);
}

样本输出

The quick brown fox jumped over the lazy dog. ���������0LãUˇ���∞4 ����������@LãUˇ��������������

注意到句子后面的所有垃圾了吗?我不确定是什么原因造成的。

提前感谢您的帮助

【问题讨论】:

  • 请贴出完整的相关代码。
  • 请发布load声明。
  • 您是否正在阅读大约 45 个字符(“The quick brown fox jumped over the lazy dog.”的长度)并打印 100 个字符?

标签: c arrays file input


【解决方案1】:

那么,当您在for 循环中打印 100 个字符时,您期望会发生什么???

  1. while 循环之前添加i = 0

  2. while 循环之后添加load[i] = 0

  3. printf("%s",load)替换整个for循环。

另外,假设load 数组被静态分配在同一个函数中:

  • &amp;&amp; i &lt; sizeof(load)-1 扩展while 循环的条件。

【讨论】:

    【解决方案2】:

    您正在为从099i 的所有值打印load[i],但似乎从未分配给它超出从文件读取的数据结束的位置。这意味着数组的其余部分有垃圾数据,这是您打印时看到的。

    要解决此问题,请在从文件读取的数据末尾添加一个终止符,并在 for 循环出现时中断它。

    【讨论】:

      【解决方案3】:

      如果你坚持保留你的 for 循环:

      for(int j = 0; j < i; ++j)  //stop at the EOF you got earlier
      {
          printf("%c", load[i]);
      }
      

      【讨论】:

        【解决方案4】:

        在 C 中,所有字符串都有一个空字符串终止符,即\0 字符。由于您已经加载了最后一个字符,i 那么您可以:

        if (i >= 100) i = 100; // bounding checks
        load[i] = '\0';
        

        对于打印,您必须:

        int pos;
        while ( pos = 0; pos < i; ++pos)
          printf("%c", load[pos]);
        

        或者……

        printf("%s", load);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多