在文件中保存字符问题
嘿。 我在使用 ofstream 将 char 写入文件时遇到一些问题。 这就是代码的样子(只是为了展示它是如何工作的。这不是真正的代码)。
char buffer[5001];
char secondbuffer[5001];
char temp;
ifstream in(Filename here);
int i = 0;
while(in.get(secondbuffer) && !in.eof[])
{
i++;
}
for(int j = 0; j < i; j++)
{
secondbuffer[j] = buffer[j];
}
ofstream fout(somefile);
fout << secondbuffer;
// end of program
问题是它可以很好地读取第一个文件的字符,但是当它写入第二个文件时,它会添加第一个文件中的所有字符,正如它应该做的那样,但是当没有更多字符时,它会添加很多字符文件末尾的“Ì”字符。
fx:
文件 1: abc
文件 2: abcÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ...
如何防止程序将“Ì”保存在文件中?
编辑2:
int i = 0;
lenghtofFile++;
while(fin.get(firstfileBuffer[i]) && !fin.eof())
{
i++;
lenghtofFile++;
}
firstfileBuffer[i] = '\0';
for(int j = 0; j < lenghtofFile; j++)
{
if(secondfileBuffer[j] != ' ' && secondfileBuffer[j] != '\0')
{
secondfileBuffer[j] = function(key, firstfileBuffer[j]);
}
}
secondfileBuffer[lenghtofFile]='\0';
fout << secondfileBuffer;
Hey.
I have some problems writing char to a file with ofstream.
this is how the code looks (Just to show how it works. This is NOT the real code).
char buffer[5001];
char secondbuffer[5001];
char temp;
ifstream in(Filename here);
int i = 0;
while(in.get(secondbuffer) && !in.eof[])
{
i++;
}
for(int j = 0; j < i; j++)
{
secondbuffer[j] = buffer[j];
}
ofstream fout(somefile);
fout << secondbuffer;
// end of program
The problem is that it reads the characters of the first file fine, but when it writes to the second file, it adds all characters from the first file, as its supposed to do, but when there are no more characters, it adds a lot of "Ì" characters in the end of file.
fx:
file 1:
abc
file 2:
abcÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ...
How can I prevent the program save "Ì" in the file?
EDIT2:
int i = 0;
lenghtofFile++;
while(fin.get(firstfileBuffer[i]) && !fin.eof())
{
i++;
lenghtofFile++;
}
firstfileBuffer[i] = '\0';
for(int j = 0; j < lenghtofFile; j++)
{
if(secondfileBuffer[j] != ' ' && secondfileBuffer[j] != '\0')
{
secondfileBuffer[j] = function(key, firstfileBuffer[j]);
}
}
secondfileBuffer[lenghtofFile]='\0';
fout << secondfileBuffer;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将第二个缓冲区设置为空终止。您将添加从流中读取的所有字符,其中不包括尾随的 NULL。
在
fout
之前的行中添加You need to null-terminate secondbuffer. You are adding all the characters read from the stream, which do not include the trailing NULL.
on the line before
fout
, add问题是您的文件中没有终止空字符。当你读入文件时,你会得到“abc”,但是声明它时位于 Secondbuffer 中的垃圾仍然存在,因此在它的开头写入“abc”意味着你有一个 5001 长度的数组以“abc”开头的垃圾。
添加
secondbuffer[i] = '\0';
。尝试在 for 循环后
The problem is that there is no terminating null character in your file. When you read the file in, you get "abc" just fine, but the garbage that was sitting in secondbuffer when it was declared is still there, so writing "abc" to the beginning of it means that you have a 5001-length array of garbage that starts with "abc."
Try adding
secondbuffer[i] = '\0';
after your for loop.这应该可以正常工作:
This should work fine: