简体   繁体   中英

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];
}

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() .

Use std::string , std::vector and std::getline and you can still return a char . That will solve your memory leak and skipping whitespace problem.

Example:

char infile()
{
  std::ifstream readFile("text.txt");
  std::vector<std::string> v;
  std::string line;
  while(std::getline(readFile, line))
  {
    v.push_back(line);
  }                                      
  for(auto& s : v)
  {
      std::cout << s << std::endl;
  }
   return (v[0])[0];
}

You are asking it to read while delimiting where there is whitespace.

You can use getline() to preserve the whitespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM