0

嘿。我在使用 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 

问题是它可以很好地读取第一个文件的字符,但是当它写入第二个文件时,它会添加第一个文件中的所有字符,就像它应该做的那样,但是当没有更多字符时,它会添加很多文件末尾的“Ì”字符。

外汇:

文件 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;
4

3 回答 3

0

这应该可以正常工作:

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
  char buffer[5001];
  char secondbuffer[5001];
  ifstream in("foo.txt", ifstream::in);
  ofstream fout("blah_copy.txt");
  do
    {
      in.getline(buffer,5001);
      fout<<buffer;
    }
  while(!in.eof());
  in.close();
  fout.close();
  return 0;
}
于 2011-02-10T20:24:39.060 回答
0

您需要空终止第二个缓冲区。您正在添加从流中读取的所有字符,其中不包括尾随 NULL。

在前一行fout,添加

secondbuffer[j]='\0\';
于 2011-02-10T19:51:19.010 回答
0

问题是您的文件中没有终止空字符。当你读入文件时,你得到“abc”就好了,但是当它被声明时坐在 secondbuffer 中的垃圾仍然存在,所以在它的开头写“abc”意味着你有一个 5001 长度的数组以“abc”开头的垃圾。

尝试添加

secondbuffer[i] = '\0';在你的 for 循环之后。

于 2011-02-10T19:52:10.880 回答