0

I'm trying to read a .txt file that uses 21 characters (image below). However when it is read and output, an extra x is present in the bottom right corner and the length of the string used to store it is 24 instead of 21. I feel like this is an obvious error but I couldn't find anything.

void readMaze(string fileName)
{
    ifstream input(fileName);
    string stringarray;
    char data;
    while (!input.eof())   //While loop used to store each individual character to the string.
    {
        input.get(data);
        stringarray += data;
    }
    cout << "The Maze being solved is: " << endl;
    cout << stringarray << endl;  // Outputs the maze to the user
    convertMaze(stringarray); //The maze is then converted to binary in this function.
    input.close();
}

Text file being read:

xxxxxxx
xA...Bx
xxxxxxx

Output:

xxxxxxx
xA...Bx
xxxxxxxx
  • tl;dr of the dupe: `eof` only returns true **after** you read beyond the end, but you still use `data` even though your last read failed – 463035818_is_not_a_number Nov 28 '20 at 15:34
  • You test whether the read has been successful **after** you have added the character to the string. So of course you get an extra bogus character in your string. – john Nov 28 '20 at 15:35
  • you should not ignore the return value of `get` – 463035818_is_not_a_number Nov 28 '20 at 15:35
  • 1
    It's a mental shift, for some reason beginners always think that you must test whether the next read will be successful `while (!input.eof())`. But that is based on a misunderstanding of how `eof` works, the correct way is to try to read and check **afterwards** whether that read was successful. `while (input.get(data))`. – john Nov 28 '20 at 15:39
  • Thank you for the comments, I’ve done some more reading on eof and get where I went wrong. Many thanks peeps – interben1234 Nov 28 '20 at 18:30

0 Answers0