2

I keep getting the following error:

Unhandled exception at 0x74BDD8A8 in FileName.exe: Microsoft C++ exception: std::out_of_range at memory location 0x004FA55C.

I've done some searching but I was not able to solve this problem. I did narrow it down to the fact that the out of range error is coming from my string fdata variable. Here is my code where error/exception occurs:

void MyClass::MyMethod10()
{
    string fdata;
    char num[100];
    int i = 0,k=0;
    unsigned int m,j=0;

    inputFile.open("sec1.txt", ios::in);
    inputFile >> fdata;
    while (j<fdata.length())
    {
       while (fdata.at(j) != '+')
       {
          if (fdata.at(j) != '*' && j<fdata.length())
          {
            num[k] = fdata.at(j);
            k++;
          }
          else
          {
             num[k] = '\0';
             m = atoi(num);
             //cout << m << endl;
             MyMethod22(m);
             k = 0;
          }
          j++;
       }
       MyMethod22(43);
       j++;  
   }
   inputFile.close();
   outputFile.open("sec2.txt", ios::out);
   while (i<index)
   {
     outputFile << (char)data[i];
     i++;
   }
   outputFile.close();
   CleanBuffer();
}

The sec1.txt file contains the following data

25750*23084*57475*15982*+57475*15982*+13364*15982*26260*+48840*32397*13364*15982*57475*11371*21876*+25197*

In the while() loop section my program is able to read the data correctly from the file. The problem/error/exception occurs at the point where my program takes in the last number from the file. I am guessing the problem is in the while() loop, but I am not able to figure out what's wrong. All I was able to do was to narrow down the error to string fdata being out of range after it reads the last number from the file. I was wondering if anyone can help me to solve this or suggest something which I might have missed?

1
  • MSVC++ has an option in the debug menu, "break on exceptions". Commented Dec 22, 2015 at 23:33

1 Answer 1

6

The actual problem you have is here:

   while (fdata.at(j) != '+')
   {
      ...
      j++;
   }

Note that you increment j, and try to read j-th character before you check if j is in range. To fix it, change it like this:

   while (j < fdata.size() && fdata.at(j) != '+')
   {
      ...
      j++;
   }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @ Ishamael and @mathematician1975 =. My problem is solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.