C++错误地读取文件

C++ Reading from file incorrectly

本文关键字:文件 读取 错误 C++      更新时间:2023-10-16

有一个问题我想得到帮助。情况如下:

我使用以下代码将一定数量的字符读取到一个字符数组中,以便稍后处理:

char str[15]; // first 16 characters that i need to get from file
  std::ifstream fin("example.txt");
  if(fin.is_open()){
      std::cout<<"File opened successfully n";
         for(int i = 0;  i<=15; i++)
         {
            fin.get(str[i]); //reading one character from file to array
         }
  }
  else{
      std::cout<<"Failed to open file";
  }

  std::cout<<str;

它对前4个甚至5个字符都很好,但当它达到8个时,它开始打印垃圾字符。

example.txt文件的内容,我从中读取文本。

The Quick Brown Fox Jumped Over The Lazy Dog The Quick Brown Fox Jumped Over The Lazy Dog 

当我读取8个字符时输出:

The Quic�j�

当我读取16个字符时输出:

The Quick Brown ASCII

为什么会发生这种情况?当我试图从文件中读取特定长度时,"ASCII"是从哪里来的?

最后,如果我想从文件中获得特定的长度,我应该使用什么样的代码?例如,如果我想阅读前4、8、16甚至20个字符?它不一定要放入char数组中,它可以保存到字符串中。

提前谢谢。

您的char数组只有15个字符长。所以这条线越界了:

for(int i = 0;  i<=15; i++)

如果i等于15,那就太多了,因为您的数组从0计数到14

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14<=数数他们!

0开始到1415个位置

此外,当字符串存储在存储器中时,它们必须由空字符''终止。否则,打印它们的函数不知道何时停止,这可能是垃圾的来源。

因此,由于null终止符占用了15中的一个空格,因此只剩下14个空格可以从文件中读取。

因此:

     for(int i = 0;  i < 14; i++)
     {
        fin.get(str[i]); //reading 14 characters (0-13)
     }
     str[14] = ''; // add the string terminator at the end of the array.

看看这是否有效。