-1

I'm struggling to find a way to both read a file to the end of a line, such as

dog \n cat \n pig

and store the char of each to an array. While I can do this for one line, I can't work out how to move on to the next line (ie dog to cat) and still register the end of the file. Here is my code so far;

searchFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            char next;
            while (searchFile.get(next))
            {
                if (next == '\n')  // If the file has been opened in
                {
                    for (int i = 0; i <= searchTempSize; i++) // ... For each character within the total length of the string ...
                    {
                        searchCharArray[i] = searchArray[i];
                        cout << searchCharArray[i] << endl;
                    }
                }     
            }

Edit for clarity: I need to read the file and store the characters of each word as an array. However, the file contains each word on a new line. I can't seem to find a way to read on to the next line, rather than end.

fauliath
  • 73
  • 9

1 Answers1

4

The conventional way to do this is with std::getline. This returns a reference to the stream; when casted to a boolean, this indicates whether the last operation on the stream was successful, e.g., non–end-of-file. So to load all lines into an array of strings, for example, you might do the following:

std::string line;
std::vector<string> lines;
while (std::getline(searchFile, line)) {
  lines.push_back(line);
}
Jon Purdy
  • 49,516
  • 7
  • 90
  • 154
  • This worked! Thank you! However, I am getting a Debug Assertion Error, although I'm sure this will be easier to rectify. – fauliath Mar 03 '16 at 23:55