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 

問題は、最初のファイルの文字を正常に読み取ることですが、2番目のファイルに書き込むと、本来のように最初のファイルからすべての文字が追加されますが、文字がなくなると、多くの文字が追加されますファイルの終わりにある「Ì」文字の。

fx:

ファイル1: abc

ファイル2: abcÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ..

プログラムがファイルに「Ì」を保存しないようにするにはどうすればよいですか?

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

3 に答える 3

0

2番目のバッファをnullで終了する必要があります。ストリームから読み取られたすべての文字を追加しますが、末尾の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 に答える
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 に答える