C++错误地读取文件
C++ Reading from file incorrectly
有一个问题我想得到帮助。情况如下:
我使用以下代码将一定数量的字符读取到一个字符数组中,以便稍后处理:
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
开始到14
有15
个位置
此外,当字符串存储在存储器中时,它们必须由空字符' '
终止。否则,打印它们的函数不知道何时停止,这可能是垃圾的来源。
因此,由于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.
看看这是否有效。
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量