开发者

Saving char in a file problems

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

f开发者_高级运维ile 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;


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

secondbuffer[j]='\0\';


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:

#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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜