-1

I keep getting the Unhandled exception when I try to get the first letter after using getline function.

Error:

Unhandled exception at 0x7535DB52 in Lab2 - Containers and Regex.exe: Microsoft C++ exception: std::out_of_range at memory location 0x00B5F43C.


class CodeMap
{
private:
    vector<string> code;
    vector<char> character;

public:
    CodeMap() { character.resize(11000); }
    ~CodeMap() {};

    void setChar(string filename)
    {
        string fileName = filename;
        ifstream fin;
        fin.open(fileName.c_str());
        string line = " ";
        char codeChar;

        while (!fin.eof())
        {
            getline(fin, line);
            codeChar = line.at(0);  //Unhandled exception, tried to use [] instead, still error.

        }
        fin.close();

    }

I wondered what is going on here.

Anyway to fix this?

Thanks for helping.

Joseph D.
  • 11,804
  • 3
  • 34
  • 67
  • 3
    https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –  Jun 19 '18 at 22:42
  • The eof() cluster-ef just doesn't matter that much, boilerplate when parsing a text file is to always skip empty lines. – Hans Passant Jun 19 '18 at 23:17

1 Answers1

0

As the linked answer says (in the comment by @NeilButterworth), you cannot use the EOF condition to determine if you can do another read, only if the last read "failed". In the code above when getline finally fails (which it will), you'll have an empty line variable, which you then do an access on.

Try to do while(std::getline(fin, line)) { ... instead. That way, when getline fails, you're not using the contents of the (empty) line.

ravnsgaard
  • 922
  • 1
  • 10
  • 20