Search code examples
c++arraysifstream

Read from a file with blank spaces in C++


I am reading from a file and passing the front of the array(pointer) back into my main function. The problem I am having is that it is not copying the blank spaces in between the words. For example Hello Hello comes out as HelloHello.

I started by using getLine instead and ran into the problems of size of the file. I set it to 500 because no files will be larger than 500, however most files will be below 500 and I am trying to get the exact size of the file.

Here is my code:

char infile()
{
   const int SIZE=500;
   char input[SIZE];
   char fromFile; 
   int i=0;

   ifstream readFile;
   readFile .open("text.txt");
   while(readFile>>fromFile)
   {
     input[i]=fromFile;
     i++;
   }
   cout<<endl;
   returnArray=new char[i];//memory leak need to solve later
   for(int j=0;j<i;j++)
   {
      returnArray[j]=input[j];
      cout<<returnArray[j];
    }
    cout<<endl;
  }
  return returnArray[0];
}

Solution

  • Depending on what your file format is, you may want to use ifstream::read() or ifstream::getline() instead.

    operator >> will attempt to 'tokenize' or 'parse' the data stream as it is being read, using whitespace as separators between tokens. You're interested in getting the raw data from the file with whitespace intact, therefore you should avoid using it. If you want to read data in one line at a time, using linefeeds as separators, you should use getline(). Otherwise use read().